pane.rs

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