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