pane.rs

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