pane.rs

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