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                // main content
1935                div()
1936                    .flex_1()
1937                    .relative()
1938                    .group("")
1939                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
1940                    .on_drag_move::<ProjectEntryId>(cx.listener(Self::handle_drag_move))
1941                    .map(|div| {
1942                        if let Some(item) = self.active_item() {
1943                            div.v_flex()
1944                                .child(self.toolbar.clone())
1945                                .child(item.to_any())
1946                        } else {
1947                            div.h_flex().size_full().justify_center().child(
1948                                Label::new("Open a file or project to get started.")
1949                                    .color(Color::Muted),
1950                            )
1951                        }
1952                    })
1953                    .child(
1954                        // drag target
1955                        div()
1956                            .z_index(1)
1957                            .invisible()
1958                            .absolute()
1959                            .bg(theme::color_alpha(
1960                                cx.theme().colors().drop_target_background,
1961                                0.75,
1962                            ))
1963                            .group_drag_over::<DraggedTab>("", |style| style.visible())
1964                            .group_drag_over::<ProjectEntryId>("", |style| style.visible())
1965                            .when_some(self.can_drop_predicate.clone(), |this, p| {
1966                                this.can_drop(move |a, cx| p(a, cx))
1967                            })
1968                            .on_drop(cx.listener(move |this, dragged_tab, cx| {
1969                                this.handle_tab_drop(dragged_tab, this.active_item_index(), cx)
1970                            }))
1971                            .on_drop(cx.listener(move |this, entry_id, cx| {
1972                                this.handle_project_entry_drop(entry_id, cx)
1973                            }))
1974                            .map(|div| match self.drag_split_direction {
1975                                None => div.top_0().left_0().right_0().bottom_0(),
1976                                Some(SplitDirection::Up) => div.top_0().left_0().right_0().h_32(),
1977                                Some(SplitDirection::Down) => {
1978                                    div.left_0().bottom_0().right_0().h_32()
1979                                }
1980                                Some(SplitDirection::Left) => {
1981                                    div.top_0().left_0().bottom_0().w_32()
1982                                }
1983                                Some(SplitDirection::Right) => {
1984                                    div.top_0().bottom_0().right_0().w_32()
1985                                }
1986                            }),
1987                    ),
1988            )
1989            .on_mouse_down(
1990                MouseButton::Navigate(NavigationDirection::Back),
1991                cx.listener(|pane, _, cx| {
1992                    if let Some(workspace) = pane.workspace.upgrade() {
1993                        let pane = cx.view().downgrade();
1994                        cx.window_context().defer(move |cx| {
1995                            workspace.update(cx, |workspace, cx| {
1996                                workspace.go_back(pane, cx).detach_and_log_err(cx)
1997                            })
1998                        })
1999                    }
2000                }),
2001            )
2002            .on_mouse_down(
2003                MouseButton::Navigate(NavigationDirection::Forward),
2004                cx.listener(|pane, _, cx| {
2005                    if let Some(workspace) = pane.workspace.upgrade() {
2006                        let pane = cx.view().downgrade();
2007                        cx.window_context().defer(move |cx| {
2008                            workspace.update(cx, |workspace, cx| {
2009                                workspace.go_forward(pane, cx).detach_and_log_err(cx)
2010                            })
2011                        })
2012                    }
2013                }),
2014            )
2015    }
2016}
2017
2018impl ItemNavHistory {
2019    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2020        self.history.push(data, self.item.clone(), cx);
2021    }
2022
2023    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2024        self.history.pop(NavigationMode::GoingBack, cx)
2025    }
2026
2027    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2028        self.history.pop(NavigationMode::GoingForward, cx)
2029    }
2030}
2031
2032impl NavHistory {
2033    pub fn for_each_entry(
2034        &self,
2035        cx: &AppContext,
2036        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2037    ) {
2038        let borrowed_history = self.0.lock();
2039        borrowed_history
2040            .forward_stack
2041            .iter()
2042            .chain(borrowed_history.backward_stack.iter())
2043            .chain(borrowed_history.closed_stack.iter())
2044            .for_each(|entry| {
2045                if let Some(project_and_abs_path) =
2046                    borrowed_history.paths_by_item.get(&entry.item.id())
2047                {
2048                    f(entry, project_and_abs_path.clone());
2049                } else if let Some(item) = entry.item.upgrade() {
2050                    if let Some(path) = item.project_path(cx) {
2051                        f(entry, (path, None));
2052                    }
2053                }
2054            })
2055    }
2056
2057    pub fn set_mode(&mut self, mode: NavigationMode) {
2058        self.0.lock().mode = mode;
2059    }
2060
2061    pub fn mode(&self) -> NavigationMode {
2062        self.0.lock().mode
2063    }
2064
2065    pub fn disable(&mut self) {
2066        self.0.lock().mode = NavigationMode::Disabled;
2067    }
2068
2069    pub fn enable(&mut self) {
2070        self.0.lock().mode = NavigationMode::Normal;
2071    }
2072
2073    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2074        let mut state = self.0.lock();
2075        let entry = match mode {
2076            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2077                return None
2078            }
2079            NavigationMode::GoingBack => &mut state.backward_stack,
2080            NavigationMode::GoingForward => &mut state.forward_stack,
2081            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2082        }
2083        .pop_back();
2084        if entry.is_some() {
2085            state.did_update(cx);
2086        }
2087        entry
2088    }
2089
2090    pub fn push<D: 'static + Send + Any>(
2091        &mut self,
2092        data: Option<D>,
2093        item: Arc<dyn WeakItemHandle>,
2094        cx: &mut WindowContext,
2095    ) {
2096        let state = &mut *self.0.lock();
2097        match state.mode {
2098            NavigationMode::Disabled => {}
2099            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2100                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2101                    state.backward_stack.pop_front();
2102                }
2103                state.backward_stack.push_back(NavigationEntry {
2104                    item,
2105                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2106                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2107                });
2108                state.forward_stack.clear();
2109            }
2110            NavigationMode::GoingBack => {
2111                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2112                    state.forward_stack.pop_front();
2113                }
2114                state.forward_stack.push_back(NavigationEntry {
2115                    item,
2116                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2117                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2118                });
2119            }
2120            NavigationMode::GoingForward => {
2121                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2122                    state.backward_stack.pop_front();
2123                }
2124                state.backward_stack.push_back(NavigationEntry {
2125                    item,
2126                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2127                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2128                });
2129            }
2130            NavigationMode::ClosingItem => {
2131                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2132                    state.closed_stack.pop_front();
2133                }
2134                state.closed_stack.push_back(NavigationEntry {
2135                    item,
2136                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2137                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2138                });
2139            }
2140        }
2141        state.did_update(cx);
2142    }
2143
2144    pub fn remove_item(&mut self, item_id: EntityId) {
2145        let mut state = self.0.lock();
2146        state.paths_by_item.remove(&item_id);
2147        state
2148            .backward_stack
2149            .retain(|entry| entry.item.id() != item_id);
2150        state
2151            .forward_stack
2152            .retain(|entry| entry.item.id() != item_id);
2153        state
2154            .closed_stack
2155            .retain(|entry| entry.item.id() != item_id);
2156    }
2157
2158    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2159        self.0.lock().paths_by_item.get(&item_id).cloned()
2160    }
2161}
2162
2163impl NavHistoryState {
2164    pub fn did_update(&self, cx: &mut WindowContext) {
2165        if let Some(pane) = self.pane.upgrade() {
2166            cx.defer(move |cx| {
2167                pane.update(cx, |pane, cx| pane.history_updated(cx));
2168            });
2169        }
2170    }
2171}
2172
2173fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2174    let path = buffer_path
2175        .as_ref()
2176        .and_then(|p| p.path.to_str())
2177        .unwrap_or(&"This buffer");
2178    let path = truncate_and_remove_front(path, 80);
2179    format!("{path} contains unsaved edits. Do you want to save it?")
2180}
2181
2182#[cfg(test)]
2183mod tests {
2184    use super::*;
2185    use crate::item::test::{TestItem, TestProjectItem};
2186    use gpui::{TestAppContext, VisualTestContext};
2187    use project::FakeFs;
2188    use settings::SettingsStore;
2189    use theme::LoadThemes;
2190
2191    #[gpui::test]
2192    async fn test_remove_active_empty(cx: &mut TestAppContext) {
2193        init_test(cx);
2194        let fs = FakeFs::new(cx.executor());
2195
2196        let project = Project::test(fs, None, cx).await;
2197        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2198        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2199
2200        pane.update(cx, |pane, cx| {
2201            assert!(pane
2202                .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2203                .is_none())
2204        });
2205    }
2206
2207    #[gpui::test]
2208    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2209        init_test(cx);
2210        let fs = FakeFs::new(cx.executor());
2211
2212        let project = Project::test(fs, None, cx).await;
2213        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2214        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2215
2216        // 1. Add with a destination index
2217        //   a. Add before the active item
2218        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2219        pane.update(cx, |pane, cx| {
2220            pane.add_item(
2221                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2222                false,
2223                false,
2224                Some(0),
2225                cx,
2226            );
2227        });
2228        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2229
2230        //   b. Add after the active item
2231        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2232        pane.update(cx, |pane, cx| {
2233            pane.add_item(
2234                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2235                false,
2236                false,
2237                Some(2),
2238                cx,
2239            );
2240        });
2241        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2242
2243        //   c. Add at the end of the item list (including off the length)
2244        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2245        pane.update(cx, |pane, cx| {
2246            pane.add_item(
2247                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2248                false,
2249                false,
2250                Some(5),
2251                cx,
2252            );
2253        });
2254        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2255
2256        // 2. Add without a destination index
2257        //   a. Add with active item at the start of the item list
2258        set_labeled_items(&pane, ["A*", "B", "C"], cx);
2259        pane.update(cx, |pane, cx| {
2260            pane.add_item(
2261                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2262                false,
2263                false,
2264                None,
2265                cx,
2266            );
2267        });
2268        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2269
2270        //   b. Add with active item at the end of the item list
2271        set_labeled_items(&pane, ["A", "B", "C*"], cx);
2272        pane.update(cx, |pane, cx| {
2273            pane.add_item(
2274                Box::new(cx.build_view(|cx| TestItem::new(cx).with_label("D"))),
2275                false,
2276                false,
2277                None,
2278                cx,
2279            );
2280        });
2281        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2282    }
2283
2284    #[gpui::test]
2285    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2286        init_test(cx);
2287        let fs = FakeFs::new(cx.executor());
2288
2289        let project = Project::test(fs, None, cx).await;
2290        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2291        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2292
2293        // 1. Add with a destination index
2294        //   1a. Add before the active item
2295        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2296        pane.update(cx, |pane, cx| {
2297            pane.add_item(d, false, false, Some(0), cx);
2298        });
2299        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2300
2301        //   1b. Add after the active item
2302        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2303        pane.update(cx, |pane, cx| {
2304            pane.add_item(d, false, false, Some(2), cx);
2305        });
2306        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2307
2308        //   1c. Add at the end of the item list (including off the length)
2309        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2310        pane.update(cx, |pane, cx| {
2311            pane.add_item(a, false, false, Some(5), cx);
2312        });
2313        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2314
2315        //   1d. Add same item to active index
2316        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2317        pane.update(cx, |pane, cx| {
2318            pane.add_item(b, false, false, Some(1), cx);
2319        });
2320        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2321
2322        //   1e. Add item to index after same item in last position
2323        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2324        pane.update(cx, |pane, cx| {
2325            pane.add_item(c, false, false, Some(2), cx);
2326        });
2327        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2328
2329        // 2. Add without a destination index
2330        //   2a. Add with active item at the start of the item list
2331        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2332        pane.update(cx, |pane, cx| {
2333            pane.add_item(d, false, false, None, cx);
2334        });
2335        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2336
2337        //   2b. Add with active item at the end of the item list
2338        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2339        pane.update(cx, |pane, cx| {
2340            pane.add_item(a, false, false, None, cx);
2341        });
2342        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2343
2344        //   2c. Add active item to active item at end of list
2345        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2346        pane.update(cx, |pane, cx| {
2347            pane.add_item(c, false, false, None, cx);
2348        });
2349        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2350
2351        //   2d. Add active item to active item at start of list
2352        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2353        pane.update(cx, |pane, cx| {
2354            pane.add_item(a, false, false, None, cx);
2355        });
2356        assert_item_labels(&pane, ["A*", "B", "C"], cx);
2357    }
2358
2359    #[gpui::test]
2360    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2361        init_test(cx);
2362        let fs = FakeFs::new(cx.executor());
2363
2364        let project = Project::test(fs, None, cx).await;
2365        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2366        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2367
2368        // singleton view
2369        pane.update(cx, |pane, cx| {
2370            pane.add_item(
2371                Box::new(cx.build_view(|cx| {
2372                    TestItem::new(cx)
2373                        .with_singleton(true)
2374                        .with_label("buffer 1")
2375                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
2376                })),
2377                false,
2378                false,
2379                None,
2380                cx,
2381            );
2382        });
2383        assert_item_labels(&pane, ["buffer 1*"], cx);
2384
2385        // new singleton view with the same project entry
2386        pane.update(cx, |pane, cx| {
2387            pane.add_item(
2388                Box::new(cx.build_view(|cx| {
2389                    TestItem::new(cx)
2390                        .with_singleton(true)
2391                        .with_label("buffer 1")
2392                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2393                })),
2394                false,
2395                false,
2396                None,
2397                cx,
2398            );
2399        });
2400        assert_item_labels(&pane, ["buffer 1*"], cx);
2401
2402        // new singleton view with different project entry
2403        pane.update(cx, |pane, cx| {
2404            pane.add_item(
2405                Box::new(cx.build_view(|cx| {
2406                    TestItem::new(cx)
2407                        .with_singleton(true)
2408                        .with_label("buffer 2")
2409                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
2410                })),
2411                false,
2412                false,
2413                None,
2414                cx,
2415            );
2416        });
2417        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2418
2419        // new multibuffer view with the same project entry
2420        pane.update(cx, |pane, cx| {
2421            pane.add_item(
2422                Box::new(cx.build_view(|cx| {
2423                    TestItem::new(cx)
2424                        .with_singleton(false)
2425                        .with_label("multibuffer 1")
2426                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2427                })),
2428                false,
2429                false,
2430                None,
2431                cx,
2432            );
2433        });
2434        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2435
2436        // another multibuffer view with the same project entry
2437        pane.update(cx, |pane, cx| {
2438            pane.add_item(
2439                Box::new(cx.build_view(|cx| {
2440                    TestItem::new(cx)
2441                        .with_singleton(false)
2442                        .with_label("multibuffer 1b")
2443                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2444                })),
2445                false,
2446                false,
2447                None,
2448                cx,
2449            );
2450        });
2451        assert_item_labels(
2452            &pane,
2453            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2454            cx,
2455        );
2456    }
2457
2458    #[gpui::test]
2459    async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2460        init_test(cx);
2461        let fs = FakeFs::new(cx.executor());
2462
2463        let project = Project::test(fs, None, cx).await;
2464        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2465        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2466
2467        add_labeled_item(&pane, "A", false, cx);
2468        add_labeled_item(&pane, "B", false, cx);
2469        add_labeled_item(&pane, "C", false, cx);
2470        add_labeled_item(&pane, "D", false, cx);
2471        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2472
2473        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2474        add_labeled_item(&pane, "1", false, cx);
2475        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2476
2477        pane.update(cx, |pane, cx| {
2478            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2479        })
2480        .unwrap()
2481        .await
2482        .unwrap();
2483        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2484
2485        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2486        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2487
2488        pane.update(cx, |pane, cx| {
2489            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2490        })
2491        .unwrap()
2492        .await
2493        .unwrap();
2494        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2495
2496        pane.update(cx, |pane, cx| {
2497            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2498        })
2499        .unwrap()
2500        .await
2501        .unwrap();
2502        assert_item_labels(&pane, ["A", "C*"], cx);
2503
2504        pane.update(cx, |pane, cx| {
2505            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2506        })
2507        .unwrap()
2508        .await
2509        .unwrap();
2510        assert_item_labels(&pane, ["A*"], cx);
2511    }
2512
2513    #[gpui::test]
2514    async fn test_close_inactive_items(cx: &mut TestAppContext) {
2515        init_test(cx);
2516        let fs = FakeFs::new(cx.executor());
2517
2518        let project = Project::test(fs, None, cx).await;
2519        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2520        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2521
2522        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2523
2524        pane.update(cx, |pane, cx| {
2525            pane.close_inactive_items(&CloseInactiveItems, cx)
2526        })
2527        .unwrap()
2528        .await
2529        .unwrap();
2530        assert_item_labels(&pane, ["C*"], cx);
2531    }
2532
2533    #[gpui::test]
2534    async fn test_close_clean_items(cx: &mut TestAppContext) {
2535        init_test(cx);
2536        let fs = FakeFs::new(cx.executor());
2537
2538        let project = Project::test(fs, None, cx).await;
2539        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2540        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2541
2542        add_labeled_item(&pane, "A", true, cx);
2543        add_labeled_item(&pane, "B", false, cx);
2544        add_labeled_item(&pane, "C", true, cx);
2545        add_labeled_item(&pane, "D", false, cx);
2546        add_labeled_item(&pane, "E", false, cx);
2547        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2548
2549        pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2550            .unwrap()
2551            .await
2552            .unwrap();
2553        assert_item_labels(&pane, ["A^", "C*^"], cx);
2554    }
2555
2556    #[gpui::test]
2557    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2558        init_test(cx);
2559        let fs = FakeFs::new(cx.executor());
2560
2561        let project = Project::test(fs, None, cx).await;
2562        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2563        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2564
2565        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2566
2567        pane.update(cx, |pane, cx| {
2568            pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2569        })
2570        .unwrap()
2571        .await
2572        .unwrap();
2573        assert_item_labels(&pane, ["C*", "D", "E"], cx);
2574    }
2575
2576    #[gpui::test]
2577    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2578        init_test(cx);
2579        let fs = FakeFs::new(cx.executor());
2580
2581        let project = Project::test(fs, None, cx).await;
2582        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2583        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2584
2585        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2586
2587        pane.update(cx, |pane, cx| {
2588            pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2589        })
2590        .unwrap()
2591        .await
2592        .unwrap();
2593        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2594    }
2595
2596    #[gpui::test]
2597    async fn test_close_all_items(cx: &mut TestAppContext) {
2598        init_test(cx);
2599        let fs = FakeFs::new(cx.executor());
2600
2601        let project = Project::test(fs, None, cx).await;
2602        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2603        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2604
2605        add_labeled_item(&pane, "A", false, cx);
2606        add_labeled_item(&pane, "B", false, cx);
2607        add_labeled_item(&pane, "C", false, cx);
2608        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2609
2610        pane.update(cx, |pane, cx| {
2611            pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2612        })
2613        .unwrap()
2614        .await
2615        .unwrap();
2616        assert_item_labels(&pane, [], cx);
2617
2618        add_labeled_item(&pane, "A", true, cx);
2619        add_labeled_item(&pane, "B", true, cx);
2620        add_labeled_item(&pane, "C", true, cx);
2621        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2622
2623        let save = pane
2624            .update(cx, |pane, cx| {
2625                pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2626            })
2627            .unwrap();
2628
2629        cx.executor().run_until_parked();
2630        cx.simulate_prompt_answer(2);
2631        save.await.unwrap();
2632        assert_item_labels(&pane, [], cx);
2633    }
2634
2635    fn init_test(cx: &mut TestAppContext) {
2636        cx.update(|cx| {
2637            let settings_store = SettingsStore::test(cx);
2638            cx.set_global(settings_store);
2639            theme::init(LoadThemes::JustBase, cx);
2640            crate::init_settings(cx);
2641            Project::init_settings(cx);
2642        });
2643    }
2644
2645    fn add_labeled_item(
2646        pane: &View<Pane>,
2647        label: &str,
2648        is_dirty: bool,
2649        cx: &mut VisualTestContext,
2650    ) -> Box<View<TestItem>> {
2651        pane.update(cx, |pane, cx| {
2652            let labeled_item = Box::new(
2653                cx.build_view(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)),
2654            );
2655            pane.add_item(labeled_item.clone(), false, false, None, cx);
2656            labeled_item
2657        })
2658    }
2659
2660    fn set_labeled_items<const COUNT: usize>(
2661        pane: &View<Pane>,
2662        labels: [&str; COUNT],
2663        cx: &mut VisualTestContext,
2664    ) -> [Box<View<TestItem>>; COUNT] {
2665        pane.update(cx, |pane, cx| {
2666            pane.items.clear();
2667            let mut active_item_index = 0;
2668
2669            let mut index = 0;
2670            let items = labels.map(|mut label| {
2671                if label.ends_with("*") {
2672                    label = label.trim_end_matches("*");
2673                    active_item_index = index;
2674                }
2675
2676                let labeled_item =
2677                    Box::new(cx.build_view(|cx| TestItem::new(cx).with_label(label)));
2678                pane.add_item(labeled_item.clone(), false, false, None, cx);
2679                index += 1;
2680                labeled_item
2681            });
2682
2683            pane.activate_item(active_item_index, false, false, cx);
2684
2685            items
2686        })
2687    }
2688
2689    // Assert the item label, with the active item label suffixed with a '*'
2690    fn assert_item_labels<const COUNT: usize>(
2691        pane: &View<Pane>,
2692        expected_states: [&str; COUNT],
2693        cx: &mut VisualTestContext,
2694    ) {
2695        pane.update(cx, |pane, cx| {
2696            let actual_states = pane
2697                .items
2698                .iter()
2699                .enumerate()
2700                .map(|(ix, item)| {
2701                    let mut state = item
2702                        .to_any()
2703                        .downcast::<TestItem>()
2704                        .unwrap()
2705                        .read(cx)
2706                        .label
2707                        .clone();
2708                    if ix == pane.active_item_index {
2709                        state.push('*');
2710                    }
2711                    if item.is_dirty(cx) {
2712                        state.push('^');
2713                    }
2714                    state
2715                })
2716                .collect::<Vec<_>>();
2717
2718            assert_eq!(
2719                actual_states, expected_states,
2720                "pane items do not match expectation"
2721            );
2722        })
2723    }
2724}
2725
2726impl Render for DraggedTab {
2727    type Element = <Tab as RenderOnce>::Rendered;
2728
2729    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2730        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
2731        let item = &self.pane.read(cx).items[self.ix];
2732        let label = item.tab_content(Some(self.detail), false, cx);
2733        Tab::new("")
2734            .selected(self.is_active)
2735            .child(label)
2736            .render(cx)
2737            .font(ui_font)
2738    }
2739}