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(index_to_activate, should_activate, should_activate, cx);
1132            }
1133        }
1134
1135        let item = self.items.remove(item_index);
1136
1137        cx.emit(Event::RemoveItem {
1138            item_id: item.item_id(),
1139        });
1140        if self.items.is_empty() {
1141            item.deactivated(cx);
1142            self.update_toolbar(cx);
1143            cx.emit(Event::Remove);
1144        }
1145
1146        if item_index < self.active_item_index {
1147            self.active_item_index -= 1;
1148        }
1149
1150        self.nav_history.set_mode(NavigationMode::ClosingItem);
1151        item.deactivated(cx);
1152        self.nav_history.set_mode(NavigationMode::Normal);
1153
1154        if let Some(path) = item.project_path(cx) {
1155            let abs_path = self
1156                .nav_history
1157                .0
1158                .lock()
1159                .paths_by_item
1160                .get(&item.item_id())
1161                .and_then(|(_, abs_path)| abs_path.clone());
1162
1163            self.nav_history
1164                .0
1165                .lock()
1166                .paths_by_item
1167                .insert(item.item_id(), (path, abs_path));
1168        } else {
1169            self.nav_history
1170                .0
1171                .lock()
1172                .paths_by_item
1173                .remove(&item.item_id());
1174        }
1175
1176        if self.items.is_empty() && self.zoomed {
1177            cx.emit(Event::ZoomOut);
1178        }
1179
1180        cx.notify();
1181    }
1182
1183    pub async fn save_item(
1184        project: Model<Project>,
1185        pane: &WeakView<Pane>,
1186        item_ix: usize,
1187        item: &dyn ItemHandle,
1188        save_intent: SaveIntent,
1189        cx: &mut AsyncWindowContext,
1190    ) -> Result<bool> {
1191        const CONFLICT_MESSAGE: &str =
1192                "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1193
1194        if save_intent == SaveIntent::Skip {
1195            return Ok(true);
1196        }
1197
1198        let (mut has_conflict, mut is_dirty, mut can_save, can_save_as) = cx.update(|_, cx| {
1199            (
1200                item.has_conflict(cx),
1201                item.is_dirty(cx),
1202                item.can_save(cx),
1203                item.is_singleton(cx),
1204            )
1205        })?;
1206
1207        // when saving a single buffer, we ignore whether or not it's dirty.
1208        if save_intent == SaveIntent::Save {
1209            is_dirty = true;
1210        }
1211
1212        if save_intent == SaveIntent::SaveAs {
1213            is_dirty = true;
1214            has_conflict = false;
1215            can_save = false;
1216        }
1217
1218        if save_intent == SaveIntent::Overwrite {
1219            has_conflict = false;
1220        }
1221
1222        if has_conflict && can_save {
1223            let answer = pane.update(cx, |pane, cx| {
1224                pane.activate_item(item_ix, true, true, cx);
1225                cx.prompt(
1226                    PromptLevel::Warning,
1227                    CONFLICT_MESSAGE,
1228                    &["Overwrite", "Discard", "Cancel"],
1229                )
1230            })?;
1231            match answer.await {
1232                Ok(0) => pane.update(cx, |_, cx| item.save(project, cx))?.await?,
1233                Ok(1) => pane.update(cx, |_, cx| item.reload(project, cx))?.await?,
1234                _ => return Ok(false),
1235            }
1236        } else if is_dirty && (can_save || can_save_as) {
1237            if save_intent == SaveIntent::Close {
1238                let will_autosave = cx.update(|_, cx| {
1239                    matches!(
1240                        WorkspaceSettings::get_global(cx).autosave,
1241                        AutosaveSetting::OnFocusChange | AutosaveSetting::OnWindowChange
1242                    ) && Self::can_autosave_item(&*item, cx)
1243                })?;
1244                if !will_autosave {
1245                    let answer = pane.update(cx, |pane, cx| {
1246                        pane.activate_item(item_ix, true, true, cx);
1247                        let prompt = dirty_message_for(item.project_path(cx));
1248                        cx.prompt(
1249                            PromptLevel::Warning,
1250                            &prompt,
1251                            &["Save", "Don't Save", "Cancel"],
1252                        )
1253                    })?;
1254                    match answer.await {
1255                        Ok(0) => {}
1256                        Ok(1) => return Ok(true), // Don't save this file
1257                        _ => return Ok(false),    // Cancel
1258                    }
1259                }
1260            }
1261
1262            if can_save {
1263                pane.update(cx, |_, cx| item.save(project, cx))?.await?;
1264            } else if can_save_as {
1265                let start_abs_path = project
1266                    .update(cx, |project, cx| {
1267                        let worktree = project.visible_worktrees(cx).next()?;
1268                        Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1269                    })?
1270                    .unwrap_or_else(|| Path::new("").into());
1271
1272                let abs_path = cx.update(|_, cx| cx.prompt_for_new_path(&start_abs_path))?;
1273                if let Some(abs_path) = abs_path.await.ok().flatten() {
1274                    pane.update(cx, |_, cx| item.save_as(project, abs_path, cx))?
1275                        .await?;
1276                } else {
1277                    return Ok(false);
1278                }
1279            }
1280        }
1281        Ok(true)
1282    }
1283
1284    fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
1285        let is_deleted = item.project_entry_ids(cx).is_empty();
1286        item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
1287    }
1288
1289    pub fn autosave_item(
1290        item: &dyn ItemHandle,
1291        project: Model<Project>,
1292        cx: &mut WindowContext,
1293    ) -> Task<Result<()>> {
1294        if Self::can_autosave_item(item, cx) {
1295            item.save(project, cx)
1296        } else {
1297            Task::ready(Ok(()))
1298        }
1299    }
1300
1301    pub fn focus(&mut self, cx: &mut ViewContext<Pane>) {
1302        cx.focus(&self.focus_handle);
1303    }
1304
1305    pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
1306        if let Some(active_item) = self.active_item() {
1307            let focus_handle = active_item.focus_handle(cx);
1308            cx.focus(&focus_handle);
1309        }
1310    }
1311
1312    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
1313        cx.emit(Event::Split(direction));
1314    }
1315
1316    //     fn deploy_split_menu(&mut self, cx: &mut ViewContext<Self>) {
1317    //         self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1318    //             menu.toggle(
1319    //                 Default::default(),
1320    //                 AnchorCorner::TopRight,
1321    //                 vec![
1322    //                     ContextMenuItem::action("Split Right", SplitRight),
1323    //                     ContextMenuItem::action("Split Left", SplitLeft),
1324    //                     ContextMenuItem::action("Split Up", SplitUp),
1325    //                     ContextMenuItem::action("Split Down", SplitDown),
1326    //                 ],
1327    //                 cx,
1328    //             );
1329    //         });
1330
1331    //         self.tab_bar_context_menu.kind = TabBarContextMenuKind::Split;
1332    //     }
1333
1334    //     fn deploy_new_menu(&mut self, cx: &mut ViewContext<Self>) {
1335    //         self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1336    //             menu.toggle(
1337    //                 Default::default(),
1338    //                 AnchorCorner::TopRight,
1339    //                 vec![
1340    //                     ContextMenuItem::action("New File", NewFile),
1341    //                     ContextMenuItem::action("New Terminal", NewCenterTerminal),
1342    //                     ContextMenuItem::action("New Search", NewSearch),
1343    //                 ],
1344    //                 cx,
1345    //             );
1346    //         });
1347
1348    //         self.tab_bar_context_menu.kind = TabBarContextMenuKind::New;
1349    //     }
1350
1351    //     fn deploy_tab_context_menu(
1352    //         &mut self,
1353    //         position: Vector2F,
1354    //         target_item_id: usize,
1355    //         cx: &mut ViewContext<Self>,
1356    //     ) {
1357    //         let active_item_id = self.items[self.active_item_index].id();
1358    //         let is_active_item = target_item_id == active_item_id;
1359    //         let target_pane = cx.weak_handle();
1360
1361    //         // 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
1362
1363    //         self.tab_context_menu.update(cx, |menu, cx| {
1364    //             menu.show(
1365    //                 position,
1366    //                 AnchorCorner::TopLeft,
1367    //                 if is_active_item {
1368    //                     vec![
1369    //                         ContextMenuItem::action(
1370    //                             "Close Active Item",
1371    //                             CloseActiveItem { save_intent: None },
1372    //                         ),
1373    //                         ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1374    //                         ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1375    //                         ContextMenuItem::action("Close Items To The Left", CloseItemsToTheLeft),
1376    //                         ContextMenuItem::action("Close Items To The Right", CloseItemsToTheRight),
1377    //                         ContextMenuItem::action(
1378    //                             "Close All Items",
1379    //                             CloseAllItems { save_intent: None },
1380    //                         ),
1381    //                     ]
1382    //                 } else {
1383    //                     // 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.
1384    //                     vec![
1385    //                         ContextMenuItem::handler("Close Inactive Item", {
1386    //                             let pane = target_pane.clone();
1387    //                             move |cx| {
1388    //                                 if let Some(pane) = pane.upgrade(cx) {
1389    //                                     pane.update(cx, |pane, cx| {
1390    //                                         pane.close_item_by_id(
1391    //                                             target_item_id,
1392    //                                             SaveIntent::Close,
1393    //                                             cx,
1394    //                                         )
1395    //                                         .detach_and_log_err(cx);
1396    //                                     })
1397    //                                 }
1398    //                             }
1399    //                         }),
1400    //                         ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1401    //                         ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1402    //                         ContextMenuItem::handler("Close Items To The Left", {
1403    //                             let pane = target_pane.clone();
1404    //                             move |cx| {
1405    //                                 if let Some(pane) = pane.upgrade(cx) {
1406    //                                     pane.update(cx, |pane, cx| {
1407    //                                         pane.close_items_to_the_left_by_id(target_item_id, cx)
1408    //                                             .detach_and_log_err(cx);
1409    //                                     })
1410    //                                 }
1411    //                             }
1412    //                         }),
1413    //                         ContextMenuItem::handler("Close Items To The Right", {
1414    //                             let pane = target_pane.clone();
1415    //                             move |cx| {
1416    //                                 if let Some(pane) = pane.upgrade(cx) {
1417    //                                     pane.update(cx, |pane, cx| {
1418    //                                         pane.close_items_to_the_right_by_id(target_item_id, cx)
1419    //                                             .detach_and_log_err(cx);
1420    //                                     })
1421    //                                 }
1422    //                             }
1423    //                         }),
1424    //                         ContextMenuItem::action(
1425    //                             "Close All Items",
1426    //                             CloseAllItems { save_intent: None },
1427    //                         ),
1428    //                     ]
1429    //                 },
1430    //                 cx,
1431    //             );
1432    //         });
1433    //     }
1434
1435    pub fn toolbar(&self) -> &View<Toolbar> {
1436        &self.toolbar
1437    }
1438
1439    pub fn handle_deleted_project_item(
1440        &mut self,
1441        entry_id: ProjectEntryId,
1442        cx: &mut ViewContext<Pane>,
1443    ) -> Option<()> {
1444        let (item_index_to_delete, item_id) = self.items().enumerate().find_map(|(i, item)| {
1445            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
1446                Some((i, item.item_id()))
1447            } else {
1448                None
1449            }
1450        })?;
1451
1452        self.remove_item(item_index_to_delete, false, cx);
1453        self.nav_history.remove_item(item_id);
1454
1455        Some(())
1456    }
1457
1458    fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1459        let active_item = self
1460            .items
1461            .get(self.active_item_index)
1462            .map(|item| item.as_ref());
1463        self.toolbar.update(cx, |toolbar, cx| {
1464            toolbar.set_active_item(active_item, cx);
1465        });
1466    }
1467
1468    fn update_status_bar(&mut self, cx: &mut ViewContext<Self>) {
1469        let workspace = self.workspace.clone();
1470        let pane = cx.view().clone();
1471
1472        cx.window_context().defer(move |cx| {
1473            let Ok(status_bar) = workspace.update(cx, |workspace, _| workspace.status_bar.clone())
1474            else {
1475                return;
1476            };
1477
1478            status_bar.update(cx, move |status_bar, cx| {
1479                status_bar.set_active_pane(&pane, cx);
1480            });
1481        });
1482    }
1483
1484    fn render_tab(
1485        &self,
1486        ix: usize,
1487        item: &Box<dyn ItemHandle>,
1488        detail: usize,
1489        cx: &mut ViewContext<'_, Pane>,
1490    ) -> impl IntoElement {
1491        let is_active = ix == self.active_item_index;
1492
1493        let label = item.tab_content(Some(detail), is_active, cx);
1494        let close_side = &ItemSettings::get_global(cx).close_position;
1495
1496        let indicator = maybe!({
1497            let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
1498                (true, _) => Color::Warning,
1499                (_, true) => Color::Accent,
1500                (false, false) => return None,
1501            };
1502
1503            Some(Indicator::dot().color(indicator_color))
1504        });
1505
1506        let item_id = item.item_id();
1507        let is_first_item = ix == 0;
1508        let is_last_item = ix == self.items.len() - 1;
1509        let position_relative_to_active_item = ix.cmp(&self.active_item_index);
1510
1511        let tab = Tab::new(ix)
1512            .position(if is_first_item {
1513                TabPosition::First
1514            } else if is_last_item {
1515                TabPosition::Last
1516            } else {
1517                TabPosition::Middle(position_relative_to_active_item)
1518            })
1519            .close_side(match close_side {
1520                ClosePosition::Left => ui::TabCloseSide::Start,
1521                ClosePosition::Right => ui::TabCloseSide::End,
1522            })
1523            .selected(is_active)
1524            .on_click(
1525                cx.listener(move |pane: &mut Self, _, cx| pane.activate_item(ix, true, true, cx)),
1526            )
1527            // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
1528            .on_mouse_down(
1529                MouseButton::Middle,
1530                cx.listener(move |pane, _event, cx| {
1531                    pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1532                        .detach_and_log_err(cx);
1533                }),
1534            )
1535            .on_drag(
1536                DraggedTab {
1537                    pane: cx.view().clone(),
1538                    detail,
1539                    item_id,
1540                    is_active,
1541                    ix,
1542                },
1543                |tab, cx| cx.new_view(|_| tab.clone()),
1544            )
1545            .drag_over::<DraggedTab>(|tab| tab.bg(cx.theme().colors().drop_target_background))
1546            .drag_over::<ProjectEntryId>(|tab| tab.bg(cx.theme().colors().drop_target_background))
1547            .when_some(self.can_drop_predicate.clone(), |this, p| {
1548                this.can_drop(move |a, cx| p(a, cx))
1549            })
1550            .on_drop(cx.listener(move |this, dragged_tab: &DraggedTab, cx| {
1551                this.drag_split_direction = None;
1552                this.handle_tab_drop(dragged_tab, ix, cx)
1553            }))
1554            .on_drop(cx.listener(move |this, entry_id: &ProjectEntryId, cx| {
1555                this.drag_split_direction = None;
1556                this.handle_project_entry_drop(entry_id, cx)
1557            }))
1558            .when_some(item.tab_tooltip_text(cx), |tab, text| {
1559                tab.tooltip(move |cx| Tooltip::text(text.clone(), cx))
1560            })
1561            .start_slot::<Indicator>(indicator)
1562            .end_slot(
1563                IconButton::new("close tab", Icon::Close)
1564                    .icon_color(Color::Muted)
1565                    .size(ButtonSize::None)
1566                    .icon_size(IconSize::XSmall)
1567                    .on_click(cx.listener(move |pane, _, cx| {
1568                        pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1569                            .detach_and_log_err(cx);
1570                    })),
1571            )
1572            .child(label);
1573
1574        let single_entry_to_resolve = {
1575            let item_entries = self.items[ix].project_entry_ids(cx);
1576            if item_entries.len() == 1 {
1577                Some(item_entries[0])
1578            } else {
1579                None
1580            }
1581        };
1582
1583        let pane = cx.view().downgrade();
1584        right_click_menu(ix).trigger(tab).menu(move |cx| {
1585            let pane = pane.clone();
1586            ContextMenu::build(cx, move |mut menu, cx| {
1587                if let Some(pane) = pane.upgrade() {
1588                    menu = menu
1589                        .entry(
1590                            "Close",
1591                            Some(Box::new(CloseActiveItem { save_intent: None })),
1592                            cx.handler_for(&pane, move |pane, cx| {
1593                                pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1594                                    .detach_and_log_err(cx);
1595                            }),
1596                        )
1597                        .entry(
1598                            "Close Others",
1599                            Some(Box::new(CloseInactiveItems)),
1600                            cx.handler_for(&pane, move |pane, cx| {
1601                                pane.close_items(cx, SaveIntent::Close, |id| id != item_id)
1602                                    .detach_and_log_err(cx);
1603                            }),
1604                        )
1605                        .separator()
1606                        .entry(
1607                            "Close Left",
1608                            Some(Box::new(CloseItemsToTheLeft)),
1609                            cx.handler_for(&pane, move |pane, cx| {
1610                                pane.close_items_to_the_left_by_id(item_id, cx)
1611                                    .detach_and_log_err(cx);
1612                            }),
1613                        )
1614                        .entry(
1615                            "Close Right",
1616                            Some(Box::new(CloseItemsToTheRight)),
1617                            cx.handler_for(&pane, move |pane, cx| {
1618                                pane.close_items_to_the_right_by_id(item_id, cx)
1619                                    .detach_and_log_err(cx);
1620                            }),
1621                        )
1622                        .separator()
1623                        .entry(
1624                            "Close Clean",
1625                            Some(Box::new(CloseCleanItems)),
1626                            cx.handler_for(&pane, move |pane, cx| {
1627                                pane.close_clean_items(&CloseCleanItems, cx)
1628                                    .map(|task| task.detach_and_log_err(cx));
1629                            }),
1630                        )
1631                        .entry(
1632                            "Close All",
1633                            Some(Box::new(CloseAllItems { save_intent: None })),
1634                            cx.handler_for(&pane, |pane, cx| {
1635                                pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
1636                                    .map(|task| task.detach_and_log_err(cx));
1637                            }),
1638                        );
1639
1640                    if let Some(entry) = single_entry_to_resolve {
1641                        let entry_id = entry.to_proto();
1642                        menu = menu.separator().entry(
1643                            "Reveal In Project Panel",
1644                            Some(Box::new(RevealInProjectPanel { entry_id })),
1645                            cx.handler_for(&pane, move |pane, cx| {
1646                                pane.project.update(cx, |_, cx| {
1647                                    cx.emit(project::Event::RevealInProjectPanel(
1648                                        ProjectEntryId::from_proto(entry_id),
1649                                    ))
1650                                });
1651                            }),
1652                        );
1653                    }
1654                }
1655
1656                menu
1657            })
1658        })
1659    }
1660
1661    fn render_tab_bar(&mut self, cx: &mut ViewContext<'_, Pane>) -> impl IntoElement {
1662        TabBar::new("tab_bar")
1663            .track_scroll(self.tab_bar_scroll_handle.clone())
1664            .when(self.display_nav_history_buttons, |tab_bar| {
1665                tab_bar.start_child(
1666                    h_stack()
1667                        .gap_2()
1668                        .child(
1669                            IconButton::new("navigate_backward", Icon::ArrowLeft)
1670                                .icon_size(IconSize::Small)
1671                                .on_click({
1672                                    let view = cx.view().clone();
1673                                    move |_, cx| view.update(cx, Self::navigate_backward)
1674                                })
1675                                .disabled(!self.can_navigate_backward())
1676                                .tooltip(|cx| Tooltip::for_action("Go Back", &GoBack, cx)),
1677                        )
1678                        .child(
1679                            IconButton::new("navigate_forward", Icon::ArrowRight)
1680                                .icon_size(IconSize::Small)
1681                                .on_click({
1682                                    let view = cx.view().clone();
1683                                    move |_, cx| view.update(cx, Self::navigate_backward)
1684                                })
1685                                .disabled(!self.can_navigate_forward())
1686                                .tooltip(|cx| Tooltip::for_action("Go Forward", &GoForward, cx)),
1687                        ),
1688                )
1689            })
1690            .when(self.was_focused || self.has_focus(cx), |tab_bar| {
1691                tab_bar.end_child({
1692                    let render_tab_buttons = self.render_tab_bar_buttons.clone();
1693                    render_tab_buttons(self, cx)
1694                })
1695            })
1696            .children(
1697                self.items
1698                    .iter()
1699                    .enumerate()
1700                    .zip(self.tab_details(cx))
1701                    .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1702            )
1703            .child(
1704                div()
1705                    .min_w_6()
1706                    // HACK: This empty child is currently necessary to force the drop traget to appear
1707                    // despite us setting a min width above.
1708                    .child("")
1709                    .h_full()
1710                    .flex_grow()
1711                    .drag_over::<DraggedTab>(|bar| {
1712                        bar.bg(cx.theme().colors().drop_target_background)
1713                    })
1714                    .drag_over::<ProjectEntryId>(|bar| {
1715                        bar.bg(cx.theme().colors().drop_target_background)
1716                    })
1717                    .on_drop(cx.listener(move |this, dragged_tab: &DraggedTab, cx| {
1718                        this.drag_split_direction = None;
1719                        this.handle_tab_drop(dragged_tab, this.items.len(), cx)
1720                    }))
1721                    .on_drop(cx.listener(move |this, entry_id: &ProjectEntryId, cx| {
1722                        this.drag_split_direction = None;
1723                        this.handle_project_entry_drop(entry_id, cx)
1724                    })),
1725            )
1726    }
1727
1728    fn render_menu_overlay(menu: &View<ContextMenu>) -> Div {
1729        div()
1730            .absolute()
1731            .z_index(1)
1732            .bottom_0()
1733            .right_0()
1734            .size_0()
1735            .child(overlay().anchor(AnchorCorner::TopRight).child(menu.clone()))
1736    }
1737
1738    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1739        let mut tab_details = self.items.iter().map(|_| 0).collect::<Vec<_>>();
1740
1741        let mut tab_descriptions = HashMap::default();
1742        let mut done = false;
1743        while !done {
1744            done = true;
1745
1746            // Store item indices by their tab description.
1747            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1748                if let Some(description) = item.tab_description(*detail, cx) {
1749                    if *detail == 0
1750                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1751                    {
1752                        tab_descriptions
1753                            .entry(description)
1754                            .or_insert(Vec::new())
1755                            .push(ix);
1756                    }
1757                }
1758            }
1759
1760            // If two or more items have the same tab description, increase eir level
1761            // of detail and try again.
1762            for (_, item_ixs) in tab_descriptions.drain() {
1763                if item_ixs.len() > 1 {
1764                    done = false;
1765                    for ix in item_ixs {
1766                        tab_details[ix] += 1;
1767                    }
1768                }
1769            }
1770        }
1771
1772        tab_details
1773    }
1774
1775    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1776        self.zoomed = zoomed;
1777        cx.notify();
1778    }
1779
1780    pub fn is_zoomed(&self) -> bool {
1781        self.zoomed
1782    }
1783
1784    fn handle_drag_move<T>(&mut self, event: &DragMoveEvent<T>, cx: &mut ViewContext<Self>) {
1785        if !self.can_split {
1786            return;
1787        }
1788
1789        let edge_width = cx.rem_size() * 8;
1790        let cursor = event.event.position;
1791        let direction = if cursor.x < event.bounds.left() + edge_width {
1792            Some(SplitDirection::Left)
1793        } else if cursor.x > event.bounds.right() - edge_width {
1794            Some(SplitDirection::Right)
1795        } else if cursor.y < event.bounds.top() + edge_width {
1796            Some(SplitDirection::Up)
1797        } else if cursor.y > event.bounds.bottom() - edge_width {
1798            Some(SplitDirection::Down)
1799        } else {
1800            None
1801        };
1802
1803        if direction != self.drag_split_direction {
1804            self.drag_split_direction = direction;
1805        }
1806    }
1807
1808    fn handle_tab_drop(
1809        &mut self,
1810        dragged_tab: &DraggedTab,
1811        ix: usize,
1812        cx: &mut ViewContext<'_, Pane>,
1813    ) {
1814        let mut to_pane = cx.view().clone();
1815        let split_direction = self.drag_split_direction;
1816        let item_id = dragged_tab.item_id;
1817        let from_pane = dragged_tab.pane.clone();
1818        self.workspace
1819            .update(cx, |_, cx| {
1820                cx.defer(move |workspace, cx| {
1821                    if let Some(split_direction) = split_direction {
1822                        to_pane = workspace.split_pane(to_pane, split_direction, cx);
1823                    }
1824                    workspace.move_item(from_pane, to_pane, item_id, ix, cx);
1825                });
1826            })
1827            .log_err();
1828    }
1829
1830    fn handle_project_entry_drop(
1831        &mut self,
1832        project_entry_id: &ProjectEntryId,
1833        cx: &mut ViewContext<'_, Pane>,
1834    ) {
1835        let mut to_pane = cx.view().clone();
1836        let split_direction = self.drag_split_direction;
1837        let project_entry_id = *project_entry_id;
1838        self.workspace
1839            .update(cx, |_, cx| {
1840                cx.defer(move |workspace, cx| {
1841                    if let Some(path) = workspace
1842                        .project()
1843                        .read(cx)
1844                        .path_for_entry(project_entry_id, cx)
1845                    {
1846                        if let Some(split_direction) = split_direction {
1847                            to_pane = workspace.split_pane(to_pane, split_direction, cx);
1848                        }
1849                        workspace
1850                            .open_path(path, Some(to_pane.downgrade()), true, cx)
1851                            .detach_and_log_err(cx);
1852                    }
1853                });
1854            })
1855            .log_err();
1856    }
1857
1858    pub fn display_nav_history_buttons(&mut self, display: bool) {
1859        self.display_nav_history_buttons = display;
1860    }
1861}
1862
1863impl FocusableView for Pane {
1864    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1865        self.focus_handle.clone()
1866    }
1867}
1868
1869impl Render for Pane {
1870    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1871        v_stack()
1872            .key_context("Pane")
1873            .track_focus(&self.focus_handle)
1874            .size_full()
1875            .flex_none()
1876            .overflow_hidden()
1877            .on_action(cx.listener(|pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx)))
1878            .on_action(cx.listener(|pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)))
1879            .on_action(
1880                cx.listener(|pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)),
1881            )
1882            .on_action(cx.listener(|pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)))
1883            .on_action(cx.listener(|pane, _: &GoBack, cx| pane.navigate_backward(cx)))
1884            .on_action(cx.listener(|pane, _: &GoForward, cx| pane.navigate_forward(cx)))
1885            .on_action(cx.listener(Pane::toggle_zoom))
1886            .on_action(cx.listener(|pane: &mut Pane, action: &ActivateItem, cx| {
1887                pane.activate_item(action.0, true, true, cx);
1888            }))
1889            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateLastItem, cx| {
1890                pane.activate_item(pane.items.len() - 1, true, true, cx);
1891            }))
1892            .on_action(cx.listener(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
1893                pane.activate_prev_item(true, cx);
1894            }))
1895            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateNextItem, cx| {
1896                pane.activate_next_item(true, cx);
1897            }))
1898            .on_action(
1899                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1900                    pane.close_active_item(action, cx)
1901                        .map(|task| task.detach_and_log_err(cx));
1902                }),
1903            )
1904            .on_action(
1905                cx.listener(|pane: &mut Self, action: &CloseInactiveItems, cx| {
1906                    pane.close_inactive_items(action, cx)
1907                        .map(|task| task.detach_and_log_err(cx));
1908                }),
1909            )
1910            .on_action(
1911                cx.listener(|pane: &mut Self, action: &CloseCleanItems, cx| {
1912                    pane.close_clean_items(action, cx)
1913                        .map(|task| task.detach_and_log_err(cx));
1914                }),
1915            )
1916            .on_action(
1917                cx.listener(|pane: &mut Self, action: &CloseItemsToTheLeft, cx| {
1918                    pane.close_items_to_the_left(action, cx)
1919                        .map(|task| task.detach_and_log_err(cx));
1920                }),
1921            )
1922            .on_action(
1923                cx.listener(|pane: &mut Self, action: &CloseItemsToTheRight, cx| {
1924                    pane.close_items_to_the_right(action, cx)
1925                        .map(|task| task.detach_and_log_err(cx));
1926                }),
1927            )
1928            .on_action(cx.listener(|pane: &mut Self, action: &CloseAllItems, cx| {
1929                pane.close_all_items(action, cx)
1930                    .map(|task| task.detach_and_log_err(cx));
1931            }))
1932            .on_action(
1933                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1934                    pane.close_active_item(action, cx)
1935                        .map(|task| task.detach_and_log_err(cx));
1936                }),
1937            )
1938            .on_action(
1939                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, cx| {
1940                    pane.project.update(cx, |_, cx| {
1941                        cx.emit(project::Event::RevealInProjectPanel(
1942                            ProjectEntryId::from_proto(action.entry_id),
1943                        ))
1944                    })
1945                }),
1946            )
1947            .when(self.active_item().is_some(), |pane| {
1948                pane.child(self.render_tab_bar(cx))
1949            })
1950            .child({
1951                let has_worktrees = self.project.read(cx).worktrees().next().is_some();
1952                // main content
1953                div()
1954                    .flex_1()
1955                    .relative()
1956                    .group("")
1957                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
1958                    .on_drag_move::<ProjectEntryId>(cx.listener(Self::handle_drag_move))
1959                    .map(|div| {
1960                        if let Some(item) = self.active_item() {
1961                            div.v_flex()
1962                                .child(self.toolbar.clone())
1963                                .child(item.to_any())
1964                        } else {
1965                            let placeholder = div.h_flex().size_full().justify_center();
1966                            if has_worktrees {
1967                                placeholder
1968                            } else {
1969                                placeholder.child(
1970                                    Label::new("Open a file or project to get started.")
1971                                        .color(Color::Muted),
1972                                )
1973                            }
1974                        }
1975                    })
1976                    .child(
1977                        // drag target
1978                        div()
1979                            .z_index(1)
1980                            .invisible()
1981                            .absolute()
1982                            .bg(theme::color_alpha(
1983                                cx.theme().colors().drop_target_background,
1984                                0.75,
1985                            ))
1986                            .group_drag_over::<DraggedTab>("", |style| style.visible())
1987                            .group_drag_over::<ProjectEntryId>("", |style| style.visible())
1988                            .when_some(self.can_drop_predicate.clone(), |this, p| {
1989                                this.can_drop(move |a, cx| p(a, cx))
1990                            })
1991                            .on_drop(cx.listener(move |this, dragged_tab, cx| {
1992                                this.handle_tab_drop(dragged_tab, this.active_item_index(), cx)
1993                            }))
1994                            .on_drop(cx.listener(move |this, entry_id, cx| {
1995                                this.handle_project_entry_drop(entry_id, cx)
1996                            }))
1997                            .map(|div| match self.drag_split_direction {
1998                                None => div.top_0().left_0().right_0().bottom_0(),
1999                                Some(SplitDirection::Up) => div.top_0().left_0().right_0().h_32(),
2000                                Some(SplitDirection::Down) => {
2001                                    div.left_0().bottom_0().right_0().h_32()
2002                                }
2003                                Some(SplitDirection::Left) => {
2004                                    div.top_0().left_0().bottom_0().w_32()
2005                                }
2006                                Some(SplitDirection::Right) => {
2007                                    div.top_0().bottom_0().right_0().w_32()
2008                                }
2009                            }),
2010                    )
2011            })
2012            .on_mouse_down(
2013                MouseButton::Navigate(NavigationDirection::Back),
2014                cx.listener(|pane, _, cx| {
2015                    if let Some(workspace) = pane.workspace.upgrade() {
2016                        let pane = cx.view().downgrade();
2017                        cx.window_context().defer(move |cx| {
2018                            workspace.update(cx, |workspace, cx| {
2019                                workspace.go_back(pane, cx).detach_and_log_err(cx)
2020                            })
2021                        })
2022                    }
2023                }),
2024            )
2025            .on_mouse_down(
2026                MouseButton::Navigate(NavigationDirection::Forward),
2027                cx.listener(|pane, _, cx| {
2028                    if let Some(workspace) = pane.workspace.upgrade() {
2029                        let pane = cx.view().downgrade();
2030                        cx.window_context().defer(move |cx| {
2031                            workspace.update(cx, |workspace, cx| {
2032                                workspace.go_forward(pane, cx).detach_and_log_err(cx)
2033                            })
2034                        })
2035                    }
2036                }),
2037            )
2038    }
2039}
2040
2041impl ItemNavHistory {
2042    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2043        self.history.push(data, self.item.clone(), cx);
2044    }
2045
2046    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2047        self.history.pop(NavigationMode::GoingBack, cx)
2048    }
2049
2050    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2051        self.history.pop(NavigationMode::GoingForward, cx)
2052    }
2053}
2054
2055impl NavHistory {
2056    pub fn for_each_entry(
2057        &self,
2058        cx: &AppContext,
2059        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2060    ) {
2061        let borrowed_history = self.0.lock();
2062        borrowed_history
2063            .forward_stack
2064            .iter()
2065            .chain(borrowed_history.backward_stack.iter())
2066            .chain(borrowed_history.closed_stack.iter())
2067            .for_each(|entry| {
2068                if let Some(project_and_abs_path) =
2069                    borrowed_history.paths_by_item.get(&entry.item.id())
2070                {
2071                    f(entry, project_and_abs_path.clone());
2072                } else if let Some(item) = entry.item.upgrade() {
2073                    if let Some(path) = item.project_path(cx) {
2074                        f(entry, (path, None));
2075                    }
2076                }
2077            })
2078    }
2079
2080    pub fn set_mode(&mut self, mode: NavigationMode) {
2081        self.0.lock().mode = mode;
2082    }
2083
2084    pub fn mode(&self) -> NavigationMode {
2085        self.0.lock().mode
2086    }
2087
2088    pub fn disable(&mut self) {
2089        self.0.lock().mode = NavigationMode::Disabled;
2090    }
2091
2092    pub fn enable(&mut self) {
2093        self.0.lock().mode = NavigationMode::Normal;
2094    }
2095
2096    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2097        let mut state = self.0.lock();
2098        let entry = match mode {
2099            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2100                return None
2101            }
2102            NavigationMode::GoingBack => &mut state.backward_stack,
2103            NavigationMode::GoingForward => &mut state.forward_stack,
2104            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2105        }
2106        .pop_back();
2107        if entry.is_some() {
2108            state.did_update(cx);
2109        }
2110        entry
2111    }
2112
2113    pub fn push<D: 'static + Send + Any>(
2114        &mut self,
2115        data: Option<D>,
2116        item: Arc<dyn WeakItemHandle>,
2117        cx: &mut WindowContext,
2118    ) {
2119        let state = &mut *self.0.lock();
2120        match state.mode {
2121            NavigationMode::Disabled => {}
2122            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2123                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2124                    state.backward_stack.pop_front();
2125                }
2126                state.backward_stack.push_back(NavigationEntry {
2127                    item,
2128                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2129                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2130                });
2131                state.forward_stack.clear();
2132            }
2133            NavigationMode::GoingBack => {
2134                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2135                    state.forward_stack.pop_front();
2136                }
2137                state.forward_stack.push_back(NavigationEntry {
2138                    item,
2139                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2140                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2141                });
2142            }
2143            NavigationMode::GoingForward => {
2144                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2145                    state.backward_stack.pop_front();
2146                }
2147                state.backward_stack.push_back(NavigationEntry {
2148                    item,
2149                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2150                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2151                });
2152            }
2153            NavigationMode::ClosingItem => {
2154                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2155                    state.closed_stack.pop_front();
2156                }
2157                state.closed_stack.push_back(NavigationEntry {
2158                    item,
2159                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2160                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2161                });
2162            }
2163        }
2164        state.did_update(cx);
2165    }
2166
2167    pub fn remove_item(&mut self, item_id: EntityId) {
2168        let mut state = self.0.lock();
2169        state.paths_by_item.remove(&item_id);
2170        state
2171            .backward_stack
2172            .retain(|entry| entry.item.id() != item_id);
2173        state
2174            .forward_stack
2175            .retain(|entry| entry.item.id() != item_id);
2176        state
2177            .closed_stack
2178            .retain(|entry| entry.item.id() != item_id);
2179    }
2180
2181    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2182        self.0.lock().paths_by_item.get(&item_id).cloned()
2183    }
2184}
2185
2186impl NavHistoryState {
2187    pub fn did_update(&self, cx: &mut WindowContext) {
2188        if let Some(pane) = self.pane.upgrade() {
2189            cx.defer(move |cx| {
2190                pane.update(cx, |pane, cx| pane.history_updated(cx));
2191            });
2192        }
2193    }
2194}
2195
2196fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2197    let path = buffer_path
2198        .as_ref()
2199        .and_then(|p| p.path.to_str())
2200        .unwrap_or(&"This buffer");
2201    let path = truncate_and_remove_front(path, 80);
2202    format!("{path} contains unsaved edits. Do you want to save it?")
2203}
2204
2205#[cfg(test)]
2206mod tests {
2207    use super::*;
2208    use crate::item::test::{TestItem, TestProjectItem};
2209    use gpui::{TestAppContext, VisualTestContext};
2210    use project::FakeFs;
2211    use settings::SettingsStore;
2212    use theme::LoadThemes;
2213
2214    #[gpui::test]
2215    async fn test_remove_active_empty(cx: &mut TestAppContext) {
2216        init_test(cx);
2217        let fs = FakeFs::new(cx.executor());
2218
2219        let project = Project::test(fs, None, cx).await;
2220        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2221        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2222
2223        pane.update(cx, |pane, cx| {
2224            assert!(pane
2225                .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2226                .is_none())
2227        });
2228    }
2229
2230    #[gpui::test]
2231    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2232        init_test(cx);
2233        let fs = FakeFs::new(cx.executor());
2234
2235        let project = Project::test(fs, None, cx).await;
2236        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2237        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2238
2239        // 1. Add with a destination index
2240        //   a. Add before the active item
2241        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2242        pane.update(cx, |pane, cx| {
2243            pane.add_item(
2244                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2245                false,
2246                false,
2247                Some(0),
2248                cx,
2249            );
2250        });
2251        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2252
2253        //   b. Add after the active item
2254        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2255        pane.update(cx, |pane, cx| {
2256            pane.add_item(
2257                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2258                false,
2259                false,
2260                Some(2),
2261                cx,
2262            );
2263        });
2264        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2265
2266        //   c. Add at the end of the item list (including off the length)
2267        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2268        pane.update(cx, |pane, cx| {
2269            pane.add_item(
2270                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2271                false,
2272                false,
2273                Some(5),
2274                cx,
2275            );
2276        });
2277        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2278
2279        // 2. Add without a destination index
2280        //   a. Add with active item at the start of the item list
2281        set_labeled_items(&pane, ["A*", "B", "C"], cx);
2282        pane.update(cx, |pane, cx| {
2283            pane.add_item(
2284                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2285                false,
2286                false,
2287                None,
2288                cx,
2289            );
2290        });
2291        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2292
2293        //   b. Add with active item at the end of the item list
2294        set_labeled_items(&pane, ["A", "B", "C*"], cx);
2295        pane.update(cx, |pane, cx| {
2296            pane.add_item(
2297                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2298                false,
2299                false,
2300                None,
2301                cx,
2302            );
2303        });
2304        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2305    }
2306
2307    #[gpui::test]
2308    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2309        init_test(cx);
2310        let fs = FakeFs::new(cx.executor());
2311
2312        let project = Project::test(fs, None, cx).await;
2313        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2314        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2315
2316        // 1. Add with a destination index
2317        //   1a. Add before the active item
2318        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2319        pane.update(cx, |pane, cx| {
2320            pane.add_item(d, false, false, Some(0), cx);
2321        });
2322        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2323
2324        //   1b. Add after the active item
2325        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2326        pane.update(cx, |pane, cx| {
2327            pane.add_item(d, false, false, Some(2), cx);
2328        });
2329        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2330
2331        //   1c. Add at the end of the item list (including off the length)
2332        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2333        pane.update(cx, |pane, cx| {
2334            pane.add_item(a, false, false, Some(5), cx);
2335        });
2336        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2337
2338        //   1d. Add same item to active index
2339        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2340        pane.update(cx, |pane, cx| {
2341            pane.add_item(b, false, false, Some(1), cx);
2342        });
2343        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2344
2345        //   1e. Add item to index after same item in last position
2346        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2347        pane.update(cx, |pane, cx| {
2348            pane.add_item(c, false, false, Some(2), cx);
2349        });
2350        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2351
2352        // 2. Add without a destination index
2353        //   2a. Add with active item at the start of the item list
2354        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2355        pane.update(cx, |pane, cx| {
2356            pane.add_item(d, false, false, None, cx);
2357        });
2358        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2359
2360        //   2b. Add with active item at the end of the item list
2361        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2362        pane.update(cx, |pane, cx| {
2363            pane.add_item(a, false, false, None, cx);
2364        });
2365        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2366
2367        //   2c. Add active item to active item at end of list
2368        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2369        pane.update(cx, |pane, cx| {
2370            pane.add_item(c, false, false, None, cx);
2371        });
2372        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2373
2374        //   2d. Add active item to active item at start of list
2375        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2376        pane.update(cx, |pane, cx| {
2377            pane.add_item(a, false, false, None, cx);
2378        });
2379        assert_item_labels(&pane, ["A*", "B", "C"], cx);
2380    }
2381
2382    #[gpui::test]
2383    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2384        init_test(cx);
2385        let fs = FakeFs::new(cx.executor());
2386
2387        let project = Project::test(fs, None, cx).await;
2388        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2389        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2390
2391        // singleton view
2392        pane.update(cx, |pane, cx| {
2393            pane.add_item(
2394                Box::new(cx.new_view(|cx| {
2395                    TestItem::new(cx)
2396                        .with_singleton(true)
2397                        .with_label("buffer 1")
2398                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
2399                })),
2400                false,
2401                false,
2402                None,
2403                cx,
2404            );
2405        });
2406        assert_item_labels(&pane, ["buffer 1*"], cx);
2407
2408        // new singleton view with the same project entry
2409        pane.update(cx, |pane, cx| {
2410            pane.add_item(
2411                Box::new(cx.new_view(|cx| {
2412                    TestItem::new(cx)
2413                        .with_singleton(true)
2414                        .with_label("buffer 1")
2415                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2416                })),
2417                false,
2418                false,
2419                None,
2420                cx,
2421            );
2422        });
2423        assert_item_labels(&pane, ["buffer 1*"], cx);
2424
2425        // new singleton view with different project entry
2426        pane.update(cx, |pane, cx| {
2427            pane.add_item(
2428                Box::new(cx.new_view(|cx| {
2429                    TestItem::new(cx)
2430                        .with_singleton(true)
2431                        .with_label("buffer 2")
2432                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
2433                })),
2434                false,
2435                false,
2436                None,
2437                cx,
2438            );
2439        });
2440        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2441
2442        // new multibuffer view with the same project entry
2443        pane.update(cx, |pane, cx| {
2444            pane.add_item(
2445                Box::new(cx.new_view(|cx| {
2446                    TestItem::new(cx)
2447                        .with_singleton(false)
2448                        .with_label("multibuffer 1")
2449                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2450                })),
2451                false,
2452                false,
2453                None,
2454                cx,
2455            );
2456        });
2457        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2458
2459        // another multibuffer view with the same project entry
2460        pane.update(cx, |pane, cx| {
2461            pane.add_item(
2462                Box::new(cx.new_view(|cx| {
2463                    TestItem::new(cx)
2464                        .with_singleton(false)
2465                        .with_label("multibuffer 1b")
2466                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2467                })),
2468                false,
2469                false,
2470                None,
2471                cx,
2472            );
2473        });
2474        assert_item_labels(
2475            &pane,
2476            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2477            cx,
2478        );
2479    }
2480
2481    #[gpui::test]
2482    async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2483        init_test(cx);
2484        let fs = FakeFs::new(cx.executor());
2485
2486        let project = Project::test(fs, None, cx).await;
2487        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2488        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2489
2490        add_labeled_item(&pane, "A", false, cx);
2491        add_labeled_item(&pane, "B", false, cx);
2492        add_labeled_item(&pane, "C", false, cx);
2493        add_labeled_item(&pane, "D", false, cx);
2494        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2495
2496        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2497        add_labeled_item(&pane, "1", false, cx);
2498        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2499
2500        pane.update(cx, |pane, cx| {
2501            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2502        })
2503        .unwrap()
2504        .await
2505        .unwrap();
2506        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2507
2508        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2509        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2510
2511        pane.update(cx, |pane, cx| {
2512            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2513        })
2514        .unwrap()
2515        .await
2516        .unwrap();
2517        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2518
2519        pane.update(cx, |pane, cx| {
2520            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2521        })
2522        .unwrap()
2523        .await
2524        .unwrap();
2525        assert_item_labels(&pane, ["A", "C*"], cx);
2526
2527        pane.update(cx, |pane, cx| {
2528            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2529        })
2530        .unwrap()
2531        .await
2532        .unwrap();
2533        assert_item_labels(&pane, ["A*"], cx);
2534    }
2535
2536    #[gpui::test]
2537    async fn test_close_inactive_items(cx: &mut TestAppContext) {
2538        init_test(cx);
2539        let fs = FakeFs::new(cx.executor());
2540
2541        let project = Project::test(fs, None, cx).await;
2542        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2543        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2544
2545        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2546
2547        pane.update(cx, |pane, cx| {
2548            pane.close_inactive_items(&CloseInactiveItems, cx)
2549        })
2550        .unwrap()
2551        .await
2552        .unwrap();
2553        assert_item_labels(&pane, ["C*"], cx);
2554    }
2555
2556    #[gpui::test]
2557    async fn test_close_clean_items(cx: &mut TestAppContext) {
2558        init_test(cx);
2559        let fs = FakeFs::new(cx.executor());
2560
2561        let project = Project::test(fs, None, cx).await;
2562        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2563        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2564
2565        add_labeled_item(&pane, "A", true, cx);
2566        add_labeled_item(&pane, "B", false, cx);
2567        add_labeled_item(&pane, "C", true, cx);
2568        add_labeled_item(&pane, "D", false, cx);
2569        add_labeled_item(&pane, "E", false, cx);
2570        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2571
2572        pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2573            .unwrap()
2574            .await
2575            .unwrap();
2576        assert_item_labels(&pane, ["A^", "C*^"], cx);
2577    }
2578
2579    #[gpui::test]
2580    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2581        init_test(cx);
2582        let fs = FakeFs::new(cx.executor());
2583
2584        let project = Project::test(fs, None, cx).await;
2585        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2586        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2587
2588        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2589
2590        pane.update(cx, |pane, cx| {
2591            pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2592        })
2593        .unwrap()
2594        .await
2595        .unwrap();
2596        assert_item_labels(&pane, ["C*", "D", "E"], cx);
2597    }
2598
2599    #[gpui::test]
2600    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2601        init_test(cx);
2602        let fs = FakeFs::new(cx.executor());
2603
2604        let project = Project::test(fs, None, cx).await;
2605        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2606        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2607
2608        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2609
2610        pane.update(cx, |pane, cx| {
2611            pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2612        })
2613        .unwrap()
2614        .await
2615        .unwrap();
2616        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2617    }
2618
2619    #[gpui::test]
2620    async fn test_close_all_items(cx: &mut TestAppContext) {
2621        init_test(cx);
2622        let fs = FakeFs::new(cx.executor());
2623
2624        let project = Project::test(fs, None, cx).await;
2625        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2626        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2627
2628        add_labeled_item(&pane, "A", false, cx);
2629        add_labeled_item(&pane, "B", false, cx);
2630        add_labeled_item(&pane, "C", false, cx);
2631        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2632
2633        pane.update(cx, |pane, cx| {
2634            pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2635        })
2636        .unwrap()
2637        .await
2638        .unwrap();
2639        assert_item_labels(&pane, [], cx);
2640
2641        add_labeled_item(&pane, "A", true, cx);
2642        add_labeled_item(&pane, "B", true, cx);
2643        add_labeled_item(&pane, "C", true, cx);
2644        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2645
2646        let save = pane
2647            .update(cx, |pane, cx| {
2648                pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2649            })
2650            .unwrap();
2651
2652        cx.executor().run_until_parked();
2653        cx.simulate_prompt_answer(2);
2654        save.await.unwrap();
2655        assert_item_labels(&pane, [], cx);
2656    }
2657
2658    fn init_test(cx: &mut TestAppContext) {
2659        cx.update(|cx| {
2660            let settings_store = SettingsStore::test(cx);
2661            cx.set_global(settings_store);
2662            theme::init(LoadThemes::JustBase, cx);
2663            crate::init_settings(cx);
2664            Project::init_settings(cx);
2665        });
2666    }
2667
2668    fn add_labeled_item(
2669        pane: &View<Pane>,
2670        label: &str,
2671        is_dirty: bool,
2672        cx: &mut VisualTestContext,
2673    ) -> Box<View<TestItem>> {
2674        pane.update(cx, |pane, cx| {
2675            let labeled_item = Box::new(
2676                cx.new_view(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)),
2677            );
2678            pane.add_item(labeled_item.clone(), false, false, None, cx);
2679            labeled_item
2680        })
2681    }
2682
2683    fn set_labeled_items<const COUNT: usize>(
2684        pane: &View<Pane>,
2685        labels: [&str; COUNT],
2686        cx: &mut VisualTestContext,
2687    ) -> [Box<View<TestItem>>; COUNT] {
2688        pane.update(cx, |pane, cx| {
2689            pane.items.clear();
2690            let mut active_item_index = 0;
2691
2692            let mut index = 0;
2693            let items = labels.map(|mut label| {
2694                if label.ends_with("*") {
2695                    label = label.trim_end_matches("*");
2696                    active_item_index = index;
2697                }
2698
2699                let labeled_item = Box::new(cx.new_view(|cx| TestItem::new(cx).with_label(label)));
2700                pane.add_item(labeled_item.clone(), false, false, None, cx);
2701                index += 1;
2702                labeled_item
2703            });
2704
2705            pane.activate_item(active_item_index, false, false, cx);
2706
2707            items
2708        })
2709    }
2710
2711    // Assert the item label, with the active item label suffixed with a '*'
2712    fn assert_item_labels<const COUNT: usize>(
2713        pane: &View<Pane>,
2714        expected_states: [&str; COUNT],
2715        cx: &mut VisualTestContext,
2716    ) {
2717        pane.update(cx, |pane, cx| {
2718            let actual_states = pane
2719                .items
2720                .iter()
2721                .enumerate()
2722                .map(|(ix, item)| {
2723                    let mut state = item
2724                        .to_any()
2725                        .downcast::<TestItem>()
2726                        .unwrap()
2727                        .read(cx)
2728                        .label
2729                        .clone();
2730                    if ix == pane.active_item_index {
2731                        state.push('*');
2732                    }
2733                    if item.is_dirty(cx) {
2734                        state.push('^');
2735                    }
2736                    state
2737                })
2738                .collect::<Vec<_>>();
2739
2740            assert_eq!(
2741                actual_states, expected_states,
2742                "pane items do not match expectation"
2743            );
2744        })
2745    }
2746}
2747
2748impl Render for DraggedTab {
2749    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2750        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
2751        let item = &self.pane.read(cx).items[self.ix];
2752        let label = item.tab_content(Some(self.detail), false, cx);
2753        Tab::new("")
2754            .selected(self.is_active)
2755            .child(label)
2756            .render(cx)
2757            .font(ui_font)
2758    }
2759}