pane.rs

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