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().clone();
1575        right_click_menu(ix).trigger(tab).menu(move |cx| {
1576            let pane = pane.clone();
1577            ContextMenu::build(cx, move |menu, cx| {
1578                let menu = menu
1579                    .entry(
1580                        "Close",
1581                        Some(Box::new(CloseActiveItem { save_intent: None })),
1582                        cx.handler_for(&pane, move |pane, cx| {
1583                            pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1584                                .detach_and_log_err(cx);
1585                        }),
1586                    )
1587                    .entry(
1588                        "Close Others",
1589                        Some(Box::new(CloseInactiveItems)),
1590                        cx.handler_for(&pane, move |pane, cx| {
1591                            pane.close_items(cx, SaveIntent::Close, |id| id != item_id)
1592                                .detach_and_log_err(cx);
1593                        }),
1594                    )
1595                    .separator()
1596                    .entry(
1597                        "Close Left",
1598                        Some(Box::new(CloseItemsToTheLeft)),
1599                        cx.handler_for(&pane, move |pane, cx| {
1600                            pane.close_items_to_the_left_by_id(item_id, cx)
1601                                .detach_and_log_err(cx);
1602                        }),
1603                    )
1604                    .entry(
1605                        "Close Right",
1606                        Some(Box::new(CloseItemsToTheRight)),
1607                        cx.handler_for(&pane, move |pane, cx| {
1608                            pane.close_items_to_the_right_by_id(item_id, cx)
1609                                .detach_and_log_err(cx);
1610                        }),
1611                    )
1612                    .separator()
1613                    .entry(
1614                        "Close Clean",
1615                        Some(Box::new(CloseCleanItems)),
1616                        cx.handler_for(&pane, move |pane, cx| {
1617                            pane.close_clean_items(&CloseCleanItems, cx)
1618                                .map(|task| task.detach_and_log_err(cx));
1619                        }),
1620                    )
1621                    .entry(
1622                        "Close All",
1623                        Some(Box::new(CloseAllItems { save_intent: None })),
1624                        cx.handler_for(&pane, |pane, cx| {
1625                            pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
1626                                .map(|task| task.detach_and_log_err(cx));
1627                        }),
1628                    );
1629
1630                if let Some(entry) = single_entry_to_resolve {
1631                    let entry_id = entry.to_proto();
1632                    menu.separator().entry(
1633                        "Reveal In Project Panel",
1634                        Some(Box::new(RevealInProjectPanel { entry_id })),
1635                        cx.handler_for(&pane, move |pane, cx| {
1636                            pane.project.update(cx, |_, cx| {
1637                                cx.emit(project::Event::RevealInProjectPanel(
1638                                    ProjectEntryId::from_proto(entry_id),
1639                                ))
1640                            });
1641                        }),
1642                    )
1643                } else {
1644                    menu
1645                }
1646            })
1647        })
1648    }
1649
1650    fn render_tab_bar(&mut self, cx: &mut ViewContext<'_, Pane>) -> impl IntoElement {
1651        TabBar::new("tab_bar")
1652            .track_scroll(self.tab_bar_scroll_handle.clone())
1653            .start_child(
1654                IconButton::new("navigate_backward", Icon::ArrowLeft)
1655                    .icon_size(IconSize::Small)
1656                    .on_click({
1657                        let view = cx.view().clone();
1658                        move |_, cx| view.update(cx, Self::navigate_backward)
1659                    })
1660                    .disabled(!self.can_navigate_backward())
1661                    .tooltip(|cx| Tooltip::for_action("Go Back", &GoBack, cx)),
1662            )
1663            .start_child(
1664                IconButton::new("navigate_forward", Icon::ArrowRight)
1665                    .icon_size(IconSize::Small)
1666                    .on_click({
1667                        let view = cx.view().clone();
1668                        move |_, cx| view.update(cx, Self::navigate_backward)
1669                    })
1670                    .disabled(!self.can_navigate_forward())
1671                    .tooltip(|cx| Tooltip::for_action("Go Forward", &GoForward, cx)),
1672            )
1673            .end_child(
1674                div()
1675                    .child(
1676                        IconButton::new("plus", Icon::Plus)
1677                            .icon_size(IconSize::Small)
1678                            .on_click(cx.listener(|this, _, cx| {
1679                                let menu = ContextMenu::build(cx, |menu, _| {
1680                                    menu.action("New File", NewFile.boxed_clone())
1681                                        .action("New Terminal", NewCenterTerminal.boxed_clone())
1682                                        .action("New Search", NewSearch.boxed_clone())
1683                                });
1684                                cx.subscribe(&menu, |this, _, _: &DismissEvent, cx| {
1685                                    this.focus(cx);
1686                                    this.new_item_menu = None;
1687                                })
1688                                .detach();
1689                                this.new_item_menu = Some(menu);
1690                            }))
1691                            .tooltip(|cx| Tooltip::text("New...", cx)),
1692                    )
1693                    .when_some(self.new_item_menu.as_ref(), |el, new_item_menu| {
1694                        el.child(Self::render_menu_overlay(new_item_menu))
1695                    }),
1696            )
1697            .end_child(
1698                div()
1699                    .child(
1700                        IconButton::new("split", Icon::Split)
1701                            .icon_size(IconSize::Small)
1702                            .on_click(cx.listener(|this, _, cx| {
1703                                let menu = ContextMenu::build(cx, |menu, _| {
1704                                    menu.action("Split Right", SplitRight.boxed_clone())
1705                                        .action("Split Left", SplitLeft.boxed_clone())
1706                                        .action("Split Up", SplitUp.boxed_clone())
1707                                        .action("Split Down", SplitDown.boxed_clone())
1708                                });
1709                                cx.subscribe(&menu, |this, _, _: &DismissEvent, cx| {
1710                                    this.focus(cx);
1711                                    this.split_item_menu = None;
1712                                })
1713                                .detach();
1714                                this.split_item_menu = Some(menu);
1715                            }))
1716                            .tooltip(|cx| Tooltip::text("Split Pane", cx)),
1717                    )
1718                    .when_some(self.split_item_menu.as_ref(), |el, split_item_menu| {
1719                        el.child(Self::render_menu_overlay(split_item_menu))
1720                    }),
1721            )
1722            .children(
1723                self.items
1724                    .iter()
1725                    .enumerate()
1726                    .zip(self.tab_details(cx))
1727                    .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1728            )
1729            .child(
1730                div()
1731                    .min_w_6()
1732                    // HACK: This empty child is currently necessary to force the drop traget to appear
1733                    // despite us setting a min width above.
1734                    .child("")
1735                    .h_full()
1736                    .flex_grow()
1737                    .drag_over::<DraggedTab>(|bar| {
1738                        bar.bg(cx.theme().colors().drop_target_background)
1739                    })
1740                    .drag_over::<ProjectEntryId>(|bar| {
1741                        bar.bg(cx.theme().colors().drop_target_background)
1742                    })
1743                    .on_drop(cx.listener(move |this, dragged_tab: &DraggedTab, cx| {
1744                        this.drag_split_direction = None;
1745                        this.handle_tab_drop(dragged_tab, this.items.len(), cx)
1746                    }))
1747                    .on_drop(cx.listener(move |this, entry_id: &ProjectEntryId, cx| {
1748                        this.drag_split_direction = None;
1749                        this.handle_project_entry_drop(entry_id, cx)
1750                    })),
1751            )
1752    }
1753
1754    fn render_menu_overlay(menu: &View<ContextMenu>) -> Div {
1755        div()
1756            .absolute()
1757            .z_index(1)
1758            .bottom_0()
1759            .right_0()
1760            .size_0()
1761            .child(overlay().anchor(AnchorCorner::TopRight).child(menu.clone()))
1762    }
1763
1764    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1765        let mut tab_details = self.items.iter().map(|_| 0).collect::<Vec<_>>();
1766
1767        let mut tab_descriptions = HashMap::default();
1768        let mut done = false;
1769        while !done {
1770            done = true;
1771
1772            // Store item indices by their tab description.
1773            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1774                if let Some(description) = item.tab_description(*detail, cx) {
1775                    if *detail == 0
1776                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1777                    {
1778                        tab_descriptions
1779                            .entry(description)
1780                            .or_insert(Vec::new())
1781                            .push(ix);
1782                    }
1783                }
1784            }
1785
1786            // If two or more items have the same tab description, increase eir level
1787            // of detail and try again.
1788            for (_, item_ixs) in tab_descriptions.drain() {
1789                if item_ixs.len() > 1 {
1790                    done = false;
1791                    for ix in item_ixs {
1792                        tab_details[ix] += 1;
1793                    }
1794                }
1795            }
1796        }
1797
1798        tab_details
1799    }
1800
1801    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1802        self.zoomed = zoomed;
1803        cx.notify();
1804    }
1805
1806    pub fn is_zoomed(&self) -> bool {
1807        self.zoomed
1808    }
1809
1810    fn handle_drag_move<T>(&mut self, event: &DragMoveEvent<T>, cx: &mut ViewContext<Self>) {
1811        if !self.can_split {
1812            return;
1813        }
1814
1815        let edge_width = cx.rem_size() * 8;
1816        let cursor = event.event.position;
1817        let direction = if cursor.x < event.bounds.left() + edge_width {
1818            Some(SplitDirection::Left)
1819        } else if cursor.x > event.bounds.right() - edge_width {
1820            Some(SplitDirection::Right)
1821        } else if cursor.y < event.bounds.top() + edge_width {
1822            Some(SplitDirection::Up)
1823        } else if cursor.y > event.bounds.bottom() - edge_width {
1824            Some(SplitDirection::Down)
1825        } else {
1826            None
1827        };
1828
1829        if direction != self.drag_split_direction {
1830            self.drag_split_direction = direction;
1831        }
1832    }
1833
1834    fn handle_tab_drop(
1835        &mut self,
1836        dragged_tab: &DraggedTab,
1837        ix: usize,
1838        cx: &mut ViewContext<'_, Pane>,
1839    ) {
1840        let mut to_pane = cx.view().clone();
1841        let split_direction = self.drag_split_direction;
1842        let item_id = dragged_tab.item_id;
1843        let from_pane = dragged_tab.pane.clone();
1844        self.workspace
1845            .update(cx, |_, cx| {
1846                cx.defer(move |workspace, cx| {
1847                    if let Some(split_direction) = split_direction {
1848                        to_pane = workspace.split_pane(to_pane, split_direction, cx);
1849                    }
1850                    workspace.move_item(from_pane, to_pane, item_id, ix, cx);
1851                });
1852            })
1853            .log_err();
1854    }
1855
1856    fn handle_project_entry_drop(
1857        &mut self,
1858        project_entry_id: &ProjectEntryId,
1859        cx: &mut ViewContext<'_, Pane>,
1860    ) {
1861        let mut to_pane = cx.view().clone();
1862        let split_direction = self.drag_split_direction;
1863        let project_entry_id = *project_entry_id;
1864        self.workspace
1865            .update(cx, |_, cx| {
1866                cx.defer(move |workspace, cx| {
1867                    if let Some(path) = workspace
1868                        .project()
1869                        .read(cx)
1870                        .path_for_entry(project_entry_id, cx)
1871                    {
1872                        if let Some(split_direction) = split_direction {
1873                            to_pane = workspace.split_pane(to_pane, split_direction, cx);
1874                        }
1875                        workspace
1876                            .open_path(path, Some(to_pane.downgrade()), true, cx)
1877                            .detach_and_log_err(cx);
1878                    }
1879                });
1880            })
1881            .log_err();
1882    }
1883}
1884
1885impl FocusableView for Pane {
1886    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1887        self.focus_handle.clone()
1888    }
1889}
1890
1891impl Render for Pane {
1892    type Element = Focusable<Div>;
1893
1894    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1895        v_stack()
1896            .key_context("Pane")
1897            .track_focus(&self.focus_handle)
1898            .size_full()
1899            .flex_none()
1900            .overflow_hidden()
1901            .on_action(cx.listener(|pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx)))
1902            .on_action(cx.listener(|pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)))
1903            .on_action(
1904                cx.listener(|pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)),
1905            )
1906            .on_action(cx.listener(|pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)))
1907            .on_action(cx.listener(|pane, _: &GoBack, cx| pane.navigate_backward(cx)))
1908            .on_action(cx.listener(|pane, _: &GoForward, cx| pane.navigate_forward(cx)))
1909            .on_action(cx.listener(Pane::toggle_zoom))
1910            .on_action(cx.listener(|pane: &mut Pane, action: &ActivateItem, cx| {
1911                pane.activate_item(action.0, true, true, cx);
1912            }))
1913            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateLastItem, cx| {
1914                pane.activate_item(pane.items.len() - 1, true, true, cx);
1915            }))
1916            .on_action(cx.listener(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
1917                pane.activate_prev_item(true, cx);
1918            }))
1919            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateNextItem, cx| {
1920                pane.activate_next_item(true, cx);
1921            }))
1922            .on_action(
1923                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1924                    pane.close_active_item(action, cx)
1925                        .map(|task| task.detach_and_log_err(cx));
1926                }),
1927            )
1928            .on_action(
1929                cx.listener(|pane: &mut Self, action: &CloseInactiveItems, cx| {
1930                    pane.close_inactive_items(action, cx)
1931                        .map(|task| task.detach_and_log_err(cx));
1932                }),
1933            )
1934            .on_action(
1935                cx.listener(|pane: &mut Self, action: &CloseCleanItems, cx| {
1936                    pane.close_clean_items(action, cx)
1937                        .map(|task| task.detach_and_log_err(cx));
1938                }),
1939            )
1940            .on_action(
1941                cx.listener(|pane: &mut Self, action: &CloseItemsToTheLeft, cx| {
1942                    pane.close_items_to_the_left(action, cx)
1943                        .map(|task| task.detach_and_log_err(cx));
1944                }),
1945            )
1946            .on_action(
1947                cx.listener(|pane: &mut Self, action: &CloseItemsToTheRight, cx| {
1948                    pane.close_items_to_the_right(action, cx)
1949                        .map(|task| task.detach_and_log_err(cx));
1950                }),
1951            )
1952            .on_action(cx.listener(|pane: &mut Self, action: &CloseAllItems, cx| {
1953                pane.close_all_items(action, cx)
1954                    .map(|task| task.detach_and_log_err(cx));
1955            }))
1956            .on_action(
1957                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1958                    pane.close_active_item(action, cx)
1959                        .map(|task| task.detach_and_log_err(cx));
1960                }),
1961            )
1962            .on_action(
1963                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, cx| {
1964                    pane.project.update(cx, |_, cx| {
1965                        cx.emit(project::Event::RevealInProjectPanel(
1966                            ProjectEntryId::from_proto(action.entry_id),
1967                        ))
1968                    })
1969                }),
1970            )
1971            .child(self.render_tab_bar(cx))
1972            .child(
1973                // main content
1974                div()
1975                    .flex_1()
1976                    .relative()
1977                    .group("")
1978                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
1979                    .on_drag_move::<ProjectEntryId>(cx.listener(Self::handle_drag_move))
1980                    .map(|div| {
1981                        if let Some(item) = self.active_item() {
1982                            div.v_flex()
1983                                .child(self.toolbar.clone())
1984                                .child(item.to_any())
1985                        } else {
1986                            div.h_flex().size_full().justify_center().child(
1987                                Label::new("Open a file or project to get started.")
1988                                    .color(Color::Muted),
1989                            )
1990                        }
1991                    })
1992                    .child(
1993                        // drag target
1994                        div()
1995                            .z_index(1)
1996                            .invisible()
1997                            .absolute()
1998                            .bg(theme::color_alpha(
1999                                cx.theme().colors().drop_target_background,
2000                                0.75,
2001                            ))
2002                            .group_drag_over::<DraggedTab>("", |style| style.visible())
2003                            .group_drag_over::<ProjectEntryId>("", |style| style.visible())
2004                            .when_some(self.can_drop_predicate.clone(), |this, p| {
2005                                this.can_drop(move |a, cx| p(a, cx))
2006                            })
2007                            .on_drop(cx.listener(move |this, dragged_tab, cx| {
2008                                this.handle_tab_drop(dragged_tab, this.active_item_index(), cx)
2009                            }))
2010                            .on_drop(cx.listener(move |this, entry_id, cx| {
2011                                this.handle_project_entry_drop(entry_id, cx)
2012                            }))
2013                            .map(|div| match self.drag_split_direction {
2014                                None => div.top_0().left_0().right_0().bottom_0(),
2015                                Some(SplitDirection::Up) => div.top_0().left_0().right_0().h_32(),
2016                                Some(SplitDirection::Down) => {
2017                                    div.left_0().bottom_0().right_0().h_32()
2018                                }
2019                                Some(SplitDirection::Left) => {
2020                                    div.top_0().left_0().bottom_0().w_32()
2021                                }
2022                                Some(SplitDirection::Right) => {
2023                                    div.top_0().bottom_0().right_0().w_32()
2024                                }
2025                            }),
2026                    ),
2027            )
2028            .on_mouse_down(
2029                MouseButton::Navigate(NavigationDirection::Back),
2030                cx.listener(|pane, _, cx| {
2031                    if let Some(workspace) = pane.workspace.upgrade() {
2032                        let pane = cx.view().downgrade();
2033                        cx.window_context().defer(move |cx| {
2034                            workspace.update(cx, |workspace, cx| {
2035                                workspace.go_back(pane, cx).detach_and_log_err(cx)
2036                            })
2037                        })
2038                    }
2039                }),
2040            )
2041            .on_mouse_down(
2042                MouseButton::Navigate(NavigationDirection::Forward),
2043                cx.listener(|pane, _, cx| {
2044                    if let Some(workspace) = pane.workspace.upgrade() {
2045                        let pane = cx.view().downgrade();
2046                        cx.window_context().defer(move |cx| {
2047                            workspace.update(cx, |workspace, cx| {
2048                                workspace.go_forward(pane, cx).detach_and_log_err(cx)
2049                            })
2050                        })
2051                    }
2052                }),
2053            )
2054    }
2055}
2056
2057impl ItemNavHistory {
2058    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2059        self.history.push(data, self.item.clone(), cx);
2060    }
2061
2062    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2063        self.history.pop(NavigationMode::GoingBack, cx)
2064    }
2065
2066    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2067        self.history.pop(NavigationMode::GoingForward, cx)
2068    }
2069}
2070
2071impl NavHistory {
2072    pub fn for_each_entry(
2073        &self,
2074        cx: &AppContext,
2075        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2076    ) {
2077        let borrowed_history = self.0.lock();
2078        borrowed_history
2079            .forward_stack
2080            .iter()
2081            .chain(borrowed_history.backward_stack.iter())
2082            .chain(borrowed_history.closed_stack.iter())
2083            .for_each(|entry| {
2084                if let Some(project_and_abs_path) =
2085                    borrowed_history.paths_by_item.get(&entry.item.id())
2086                {
2087                    f(entry, project_and_abs_path.clone());
2088                } else if let Some(item) = entry.item.upgrade() {
2089                    if let Some(path) = item.project_path(cx) {
2090                        f(entry, (path, None));
2091                    }
2092                }
2093            })
2094    }
2095
2096    pub fn set_mode(&mut self, mode: NavigationMode) {
2097        self.0.lock().mode = mode;
2098    }
2099
2100    pub fn mode(&self) -> NavigationMode {
2101        self.0.lock().mode
2102    }
2103
2104    pub fn disable(&mut self) {
2105        self.0.lock().mode = NavigationMode::Disabled;
2106    }
2107
2108    pub fn enable(&mut self) {
2109        self.0.lock().mode = NavigationMode::Normal;
2110    }
2111
2112    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2113        let mut state = self.0.lock();
2114        let entry = match mode {
2115            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2116                return None
2117            }
2118            NavigationMode::GoingBack => &mut state.backward_stack,
2119            NavigationMode::GoingForward => &mut state.forward_stack,
2120            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2121        }
2122        .pop_back();
2123        if entry.is_some() {
2124            state.did_update(cx);
2125        }
2126        entry
2127    }
2128
2129    pub fn push<D: 'static + Send + Any>(
2130        &mut self,
2131        data: Option<D>,
2132        item: Arc<dyn WeakItemHandle>,
2133        cx: &mut WindowContext,
2134    ) {
2135        let state = &mut *self.0.lock();
2136        match state.mode {
2137            NavigationMode::Disabled => {}
2138            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2139                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2140                    state.backward_stack.pop_front();
2141                }
2142                state.backward_stack.push_back(NavigationEntry {
2143                    item,
2144                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2145                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2146                });
2147                state.forward_stack.clear();
2148            }
2149            NavigationMode::GoingBack => {
2150                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2151                    state.forward_stack.pop_front();
2152                }
2153                state.forward_stack.push_back(NavigationEntry {
2154                    item,
2155                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2156                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2157                });
2158            }
2159            NavigationMode::GoingForward => {
2160                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2161                    state.backward_stack.pop_front();
2162                }
2163                state.backward_stack.push_back(NavigationEntry {
2164                    item,
2165                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2166                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2167                });
2168            }
2169            NavigationMode::ClosingItem => {
2170                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2171                    state.closed_stack.pop_front();
2172                }
2173                state.closed_stack.push_back(NavigationEntry {
2174                    item,
2175                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2176                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2177                });
2178            }
2179        }
2180        state.did_update(cx);
2181    }
2182
2183    pub fn remove_item(&mut self, item_id: EntityId) {
2184        let mut state = self.0.lock();
2185        state.paths_by_item.remove(&item_id);
2186        state
2187            .backward_stack
2188            .retain(|entry| entry.item.id() != item_id);
2189        state
2190            .forward_stack
2191            .retain(|entry| entry.item.id() != item_id);
2192        state
2193            .closed_stack
2194            .retain(|entry| entry.item.id() != item_id);
2195    }
2196
2197    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2198        self.0.lock().paths_by_item.get(&item_id).cloned()
2199    }
2200}
2201
2202impl NavHistoryState {
2203    pub fn did_update(&self, cx: &mut WindowContext) {
2204        if let Some(pane) = self.pane.upgrade() {
2205            cx.defer(move |cx| {
2206                pane.update(cx, |pane, cx| pane.history_updated(cx));
2207            });
2208        }
2209    }
2210}
2211
2212fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2213    let path = buffer_path
2214        .as_ref()
2215        .and_then(|p| p.path.to_str())
2216        .unwrap_or(&"This buffer");
2217    let path = truncate_and_remove_front(path, 80);
2218    format!("{path} contains unsaved edits. Do you want to save it?")
2219}
2220
2221#[cfg(test)]
2222mod tests {
2223    use super::*;
2224    use crate::item::test::{TestItem, TestProjectItem};
2225    use gpui::{TestAppContext, VisualTestContext};
2226    use project::FakeFs;
2227    use settings::SettingsStore;
2228    use theme::LoadThemes;
2229
2230    #[gpui::test]
2231    async fn test_remove_active_empty(cx: &mut TestAppContext) {
2232        init_test(cx);
2233        let fs = FakeFs::new(cx.executor());
2234
2235        let project = Project::test(fs, None, cx).await;
2236        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2237        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2238
2239        pane.update(cx, |pane, cx| {
2240            assert!(pane
2241                .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2242                .is_none())
2243        });
2244    }
2245
2246    #[gpui::test]
2247    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2248        init_test(cx);
2249        let fs = FakeFs::new(cx.executor());
2250
2251        let project = Project::test(fs, None, cx).await;
2252        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2253        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2254
2255        // 1. Add with a destination index
2256        //   a. Add before the active item
2257        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2258        pane.update(cx, |pane, cx| {
2259            pane.add_item(
2260                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2261                false,
2262                false,
2263                Some(0),
2264                cx,
2265            );
2266        });
2267        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2268
2269        //   b. Add after the active item
2270        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2271        pane.update(cx, |pane, cx| {
2272            pane.add_item(
2273                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2274                false,
2275                false,
2276                Some(2),
2277                cx,
2278            );
2279        });
2280        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2281
2282        //   c. Add at the end of the item list (including off the length)
2283        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2284        pane.update(cx, |pane, cx| {
2285            pane.add_item(
2286                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2287                false,
2288                false,
2289                Some(5),
2290                cx,
2291            );
2292        });
2293        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2294
2295        // 2. Add without a destination index
2296        //   a. Add with active item at the start of the item list
2297        set_labeled_items(&pane, ["A*", "B", "C"], cx);
2298        pane.update(cx, |pane, cx| {
2299            pane.add_item(
2300                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2301                false,
2302                false,
2303                None,
2304                cx,
2305            );
2306        });
2307        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2308
2309        //   b. Add with active item at the end of the item list
2310        set_labeled_items(&pane, ["A", "B", "C*"], cx);
2311        pane.update(cx, |pane, cx| {
2312            pane.add_item(
2313                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2314                false,
2315                false,
2316                None,
2317                cx,
2318            );
2319        });
2320        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2321    }
2322
2323    #[gpui::test]
2324    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2325        init_test(cx);
2326        let fs = FakeFs::new(cx.executor());
2327
2328        let project = Project::test(fs, None, cx).await;
2329        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2330        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2331
2332        // 1. Add with a destination index
2333        //   1a. Add before the active item
2334        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2335        pane.update(cx, |pane, cx| {
2336            pane.add_item(d, false, false, Some(0), cx);
2337        });
2338        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2339
2340        //   1b. Add after the active item
2341        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2342        pane.update(cx, |pane, cx| {
2343            pane.add_item(d, false, false, Some(2), cx);
2344        });
2345        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2346
2347        //   1c. Add at the end of the item list (including off the length)
2348        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2349        pane.update(cx, |pane, cx| {
2350            pane.add_item(a, false, false, Some(5), cx);
2351        });
2352        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2353
2354        //   1d. Add same item to active index
2355        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2356        pane.update(cx, |pane, cx| {
2357            pane.add_item(b, false, false, Some(1), cx);
2358        });
2359        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2360
2361        //   1e. Add item to index after same item in last position
2362        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2363        pane.update(cx, |pane, cx| {
2364            pane.add_item(c, false, false, Some(2), cx);
2365        });
2366        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2367
2368        // 2. Add without a destination index
2369        //   2a. Add with active item at the start of the item list
2370        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2371        pane.update(cx, |pane, cx| {
2372            pane.add_item(d, false, false, None, cx);
2373        });
2374        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2375
2376        //   2b. Add with active item at the end of the item list
2377        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2378        pane.update(cx, |pane, cx| {
2379            pane.add_item(a, false, false, None, cx);
2380        });
2381        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2382
2383        //   2c. Add active item to active item at end of list
2384        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2385        pane.update(cx, |pane, cx| {
2386            pane.add_item(c, false, false, None, cx);
2387        });
2388        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2389
2390        //   2d. Add active item to active item at start of list
2391        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2392        pane.update(cx, |pane, cx| {
2393            pane.add_item(a, false, false, None, cx);
2394        });
2395        assert_item_labels(&pane, ["A*", "B", "C"], cx);
2396    }
2397
2398    #[gpui::test]
2399    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2400        init_test(cx);
2401        let fs = FakeFs::new(cx.executor());
2402
2403        let project = Project::test(fs, None, cx).await;
2404        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2405        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2406
2407        // singleton view
2408        pane.update(cx, |pane, cx| {
2409            pane.add_item(
2410                Box::new(cx.build_view(|cx| {
2411                    TestItem::new(cx)
2412                        .with_singleton(true)
2413                        .with_label("buffer 1")
2414                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
2415                })),
2416                false,
2417                false,
2418                None,
2419                cx,
2420            );
2421        });
2422        assert_item_labels(&pane, ["buffer 1*"], cx);
2423
2424        // new singleton view with the same project entry
2425        pane.update(cx, |pane, cx| {
2426            pane.add_item(
2427                Box::new(cx.build_view(|cx| {
2428                    TestItem::new(cx)
2429                        .with_singleton(true)
2430                        .with_label("buffer 1")
2431                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2432                })),
2433                false,
2434                false,
2435                None,
2436                cx,
2437            );
2438        });
2439        assert_item_labels(&pane, ["buffer 1*"], cx);
2440
2441        // new singleton view with different project entry
2442        pane.update(cx, |pane, cx| {
2443            pane.add_item(
2444                Box::new(cx.build_view(|cx| {
2445                    TestItem::new(cx)
2446                        .with_singleton(true)
2447                        .with_label("buffer 2")
2448                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
2449                })),
2450                false,
2451                false,
2452                None,
2453                cx,
2454            );
2455        });
2456        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2457
2458        // new multibuffer view with the same project entry
2459        pane.update(cx, |pane, cx| {
2460            pane.add_item(
2461                Box::new(cx.build_view(|cx| {
2462                    TestItem::new(cx)
2463                        .with_singleton(false)
2464                        .with_label("multibuffer 1")
2465                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2466                })),
2467                false,
2468                false,
2469                None,
2470                cx,
2471            );
2472        });
2473        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2474
2475        // another multibuffer view with the same project entry
2476        pane.update(cx, |pane, cx| {
2477            pane.add_item(
2478                Box::new(cx.build_view(|cx| {
2479                    TestItem::new(cx)
2480                        .with_singleton(false)
2481                        .with_label("multibuffer 1b")
2482                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2483                })),
2484                false,
2485                false,
2486                None,
2487                cx,
2488            );
2489        });
2490        assert_item_labels(
2491            &pane,
2492            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2493            cx,
2494        );
2495    }
2496
2497    #[gpui::test]
2498    async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2499        init_test(cx);
2500        let fs = FakeFs::new(cx.executor());
2501
2502        let project = Project::test(fs, None, cx).await;
2503        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2504        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2505
2506        add_labeled_item(&pane, "A", false, cx);
2507        add_labeled_item(&pane, "B", false, cx);
2508        add_labeled_item(&pane, "C", false, cx);
2509        add_labeled_item(&pane, "D", false, cx);
2510        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2511
2512        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2513        add_labeled_item(&pane, "1", false, cx);
2514        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2515
2516        pane.update(cx, |pane, cx| {
2517            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2518        })
2519        .unwrap()
2520        .await
2521        .unwrap();
2522        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2523
2524        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2525        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2526
2527        pane.update(cx, |pane, cx| {
2528            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2529        })
2530        .unwrap()
2531        .await
2532        .unwrap();
2533        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2534
2535        pane.update(cx, |pane, cx| {
2536            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2537        })
2538        .unwrap()
2539        .await
2540        .unwrap();
2541        assert_item_labels(&pane, ["A", "C*"], cx);
2542
2543        pane.update(cx, |pane, cx| {
2544            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2545        })
2546        .unwrap()
2547        .await
2548        .unwrap();
2549        assert_item_labels(&pane, ["A*"], cx);
2550    }
2551
2552    #[gpui::test]
2553    async fn test_close_inactive_items(cx: &mut TestAppContext) {
2554        init_test(cx);
2555        let fs = FakeFs::new(cx.executor());
2556
2557        let project = Project::test(fs, None, cx).await;
2558        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2559        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2560
2561        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2562
2563        pane.update(cx, |pane, cx| {
2564            pane.close_inactive_items(&CloseInactiveItems, cx)
2565        })
2566        .unwrap()
2567        .await
2568        .unwrap();
2569        assert_item_labels(&pane, ["C*"], cx);
2570    }
2571
2572    #[gpui::test]
2573    async fn test_close_clean_items(cx: &mut TestAppContext) {
2574        init_test(cx);
2575        let fs = FakeFs::new(cx.executor());
2576
2577        let project = Project::test(fs, None, cx).await;
2578        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2579        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2580
2581        add_labeled_item(&pane, "A", true, cx);
2582        add_labeled_item(&pane, "B", false, cx);
2583        add_labeled_item(&pane, "C", true, cx);
2584        add_labeled_item(&pane, "D", false, cx);
2585        add_labeled_item(&pane, "E", false, cx);
2586        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2587
2588        pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2589            .unwrap()
2590            .await
2591            .unwrap();
2592        assert_item_labels(&pane, ["A^", "C*^"], cx);
2593    }
2594
2595    #[gpui::test]
2596    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2597        init_test(cx);
2598        let fs = FakeFs::new(cx.executor());
2599
2600        let project = Project::test(fs, None, cx).await;
2601        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2602        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2603
2604        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2605
2606        pane.update(cx, |pane, cx| {
2607            pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2608        })
2609        .unwrap()
2610        .await
2611        .unwrap();
2612        assert_item_labels(&pane, ["C*", "D", "E"], cx);
2613    }
2614
2615    #[gpui::test]
2616    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2617        init_test(cx);
2618        let fs = FakeFs::new(cx.executor());
2619
2620        let project = Project::test(fs, None, cx).await;
2621        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2622        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2623
2624        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2625
2626        pane.update(cx, |pane, cx| {
2627            pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2628        })
2629        .unwrap()
2630        .await
2631        .unwrap();
2632        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2633    }
2634
2635    #[gpui::test]
2636    async fn test_close_all_items(cx: &mut TestAppContext) {
2637        init_test(cx);
2638        let fs = FakeFs::new(cx.executor());
2639
2640        let project = Project::test(fs, None, cx).await;
2641        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2642        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2643
2644        add_labeled_item(&pane, "A", false, cx);
2645        add_labeled_item(&pane, "B", false, cx);
2646        add_labeled_item(&pane, "C", false, cx);
2647        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2648
2649        pane.update(cx, |pane, cx| {
2650            pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2651        })
2652        .unwrap()
2653        .await
2654        .unwrap();
2655        assert_item_labels(&pane, [], cx);
2656
2657        add_labeled_item(&pane, "A", true, cx);
2658        add_labeled_item(&pane, "B", true, cx);
2659        add_labeled_item(&pane, "C", true, cx);
2660        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2661
2662        let save = pane
2663            .update(cx, |pane, cx| {
2664                pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2665            })
2666            .unwrap();
2667
2668        cx.executor().run_until_parked();
2669        cx.simulate_prompt_answer(2);
2670        save.await.unwrap();
2671        assert_item_labels(&pane, [], cx);
2672    }
2673
2674    fn init_test(cx: &mut TestAppContext) {
2675        cx.update(|cx| {
2676            let settings_store = SettingsStore::test(cx);
2677            cx.set_global(settings_store);
2678            theme::init(LoadThemes::JustBase, cx);
2679            crate::init_settings(cx);
2680            Project::init_settings(cx);
2681        });
2682    }
2683
2684    fn add_labeled_item(
2685        pane: &View<Pane>,
2686        label: &str,
2687        is_dirty: bool,
2688        cx: &mut VisualTestContext,
2689    ) -> Box<View<TestItem>> {
2690        pane.update(cx, |pane, cx| {
2691            let labeled_item = Box::new(
2692                cx.build_view(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)),
2693            );
2694            pane.add_item(labeled_item.clone(), false, false, None, cx);
2695            labeled_item
2696        })
2697    }
2698
2699    fn set_labeled_items<const COUNT: usize>(
2700        pane: &View<Pane>,
2701        labels: [&str; COUNT],
2702        cx: &mut VisualTestContext,
2703    ) -> [Box<View<TestItem>>; COUNT] {
2704        pane.update(cx, |pane, cx| {
2705            pane.items.clear();
2706            let mut active_item_index = 0;
2707
2708            let mut index = 0;
2709            let items = labels.map(|mut label| {
2710                if label.ends_with("*") {
2711                    label = label.trim_end_matches("*");
2712                    active_item_index = index;
2713                }
2714
2715                let labeled_item =
2716                    Box::new(cx.build_view(|cx| TestItem::new(cx).with_label(label)));
2717                pane.add_item(labeled_item.clone(), false, false, None, cx);
2718                index += 1;
2719                labeled_item
2720            });
2721
2722            pane.activate_item(active_item_index, false, false, cx);
2723
2724            items
2725        })
2726    }
2727
2728    // Assert the item label, with the active item label suffixed with a '*'
2729    fn assert_item_labels<const COUNT: usize>(
2730        pane: &View<Pane>,
2731        expected_states: [&str; COUNT],
2732        cx: &mut VisualTestContext,
2733    ) {
2734        pane.update(cx, |pane, cx| {
2735            let actual_states = pane
2736                .items
2737                .iter()
2738                .enumerate()
2739                .map(|(ix, item)| {
2740                    let mut state = item
2741                        .to_any()
2742                        .downcast::<TestItem>()
2743                        .unwrap()
2744                        .read(cx)
2745                        .label
2746                        .clone();
2747                    if ix == pane.active_item_index {
2748                        state.push('*');
2749                    }
2750                    if item.is_dirty(cx) {
2751                        state.push('^');
2752                    }
2753                    state
2754                })
2755                .collect::<Vec<_>>();
2756
2757            assert_eq!(
2758                actual_states, expected_states,
2759                "pane items do not match expectation"
2760            );
2761        })
2762    }
2763}
2764
2765impl Render for DraggedTab {
2766    type Element = <Tab as RenderOnce>::Rendered;
2767
2768    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2769        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
2770        let item = &self.pane.read(cx).items[self.ix];
2771        let label = item.tab_content(Some(self.detail), false, cx);
2772        Tab::new("")
2773            .selected(self.is_active)
2774            .child(label)
2775            .render(cx)
2776            .font(ui_font)
2777    }
2778}