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