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