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, IconButtonShape, IconName,
  36    IconSize, Indicator, Label, Tab, TabBar, TabPosition, Tooltip,
  37};
  38use ui::{v_flex, 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 item: Box<dyn ItemHandle>,
 223    pub ix: usize,
 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_flex()
 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                    item: item.boxed_clone(),
1314                    pane: cx.view().clone(),
1315                    detail,
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                    .shape(IconButtonShape::Square)
1345                    .icon_color(Color::Muted)
1346                    .size(ButtonSize::None)
1347                    .icon_size(IconSize::XSmall)
1348                    .on_click(cx.listener(move |pane, _, cx| {
1349                        pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1350                            .detach_and_log_err(cx);
1351                    })),
1352            )
1353            .child(label);
1354
1355        let single_entry_to_resolve = {
1356            let item_entries = self.items[ix].project_entry_ids(cx);
1357            if item_entries.len() == 1 {
1358                Some(item_entries[0])
1359            } else {
1360                None
1361            }
1362        };
1363
1364        let pane = cx.view().downgrade();
1365        right_click_menu(ix).trigger(tab).menu(move |cx| {
1366            let pane = pane.clone();
1367            ContextMenu::build(cx, move |mut menu, cx| {
1368                if let Some(pane) = pane.upgrade() {
1369                    menu = menu
1370                        .entry(
1371                            "Close",
1372                            Some(Box::new(CloseActiveItem { save_intent: None })),
1373                            cx.handler_for(&pane, move |pane, cx| {
1374                                pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1375                                    .detach_and_log_err(cx);
1376                            }),
1377                        )
1378                        .entry(
1379                            "Close Others",
1380                            Some(Box::new(CloseInactiveItems)),
1381                            cx.handler_for(&pane, move |pane, cx| {
1382                                pane.close_items(cx, SaveIntent::Close, |id| id != item_id)
1383                                    .detach_and_log_err(cx);
1384                            }),
1385                        )
1386                        .separator()
1387                        .entry(
1388                            "Close Left",
1389                            Some(Box::new(CloseItemsToTheLeft)),
1390                            cx.handler_for(&pane, move |pane, cx| {
1391                                pane.close_items_to_the_left_by_id(item_id, cx)
1392                                    .detach_and_log_err(cx);
1393                            }),
1394                        )
1395                        .entry(
1396                            "Close Right",
1397                            Some(Box::new(CloseItemsToTheRight)),
1398                            cx.handler_for(&pane, move |pane, cx| {
1399                                pane.close_items_to_the_right_by_id(item_id, cx)
1400                                    .detach_and_log_err(cx);
1401                            }),
1402                        )
1403                        .separator()
1404                        .entry(
1405                            "Close Clean",
1406                            Some(Box::new(CloseCleanItems)),
1407                            cx.handler_for(&pane, move |pane, cx| {
1408                                pane.close_clean_items(&CloseCleanItems, cx)
1409                                    .map(|task| task.detach_and_log_err(cx));
1410                            }),
1411                        )
1412                        .entry(
1413                            "Close All",
1414                            Some(Box::new(CloseAllItems { save_intent: None })),
1415                            cx.handler_for(&pane, |pane, cx| {
1416                                pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
1417                                    .map(|task| task.detach_and_log_err(cx));
1418                            }),
1419                        );
1420
1421                    if let Some(entry) = single_entry_to_resolve {
1422                        let entry_id = entry.to_proto();
1423                        menu = menu.separator().entry(
1424                            "Reveal In Project Panel",
1425                            Some(Box::new(RevealInProjectPanel { entry_id })),
1426                            cx.handler_for(&pane, move |pane, cx| {
1427                                pane.project.update(cx, |_, cx| {
1428                                    cx.emit(project::Event::RevealInProjectPanel(
1429                                        ProjectEntryId::from_proto(entry_id),
1430                                    ))
1431                                });
1432                            }),
1433                        );
1434                    }
1435                }
1436
1437                menu
1438            })
1439        })
1440    }
1441
1442    fn render_tab_bar(&mut self, cx: &mut ViewContext<'_, Pane>) -> impl IntoElement {
1443        TabBar::new("tab_bar")
1444            .track_scroll(self.tab_bar_scroll_handle.clone())
1445            .when(self.display_nav_history_buttons, |tab_bar| {
1446                tab_bar.start_child(
1447                    h_flex()
1448                        .gap_2()
1449                        .child(
1450                            IconButton::new("navigate_backward", IconName::ArrowLeft)
1451                                .icon_size(IconSize::Small)
1452                                .on_click({
1453                                    let view = cx.view().clone();
1454                                    move |_, cx| view.update(cx, Self::navigate_backward)
1455                                })
1456                                .disabled(!self.can_navigate_backward())
1457                                .tooltip(|cx| Tooltip::for_action("Go Back", &GoBack, cx)),
1458                        )
1459                        .child(
1460                            IconButton::new("navigate_forward", IconName::ArrowRight)
1461                                .icon_size(IconSize::Small)
1462                                .on_click({
1463                                    let view = cx.view().clone();
1464                                    move |_, cx| view.update(cx, Self::navigate_backward)
1465                                })
1466                                .disabled(!self.can_navigate_forward())
1467                                .tooltip(|cx| Tooltip::for_action("Go Forward", &GoForward, cx)),
1468                        ),
1469                )
1470            })
1471            .when(self.was_focused || self.has_focus(cx), |tab_bar| {
1472                tab_bar.end_child({
1473                    let render_tab_buttons = self.render_tab_bar_buttons.clone();
1474                    render_tab_buttons(self, cx)
1475                })
1476            })
1477            .children(
1478                self.items
1479                    .iter()
1480                    .enumerate()
1481                    .zip(self.tab_details(cx))
1482                    .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1483            )
1484            .child(
1485                div()
1486                    .min_w_6()
1487                    // HACK: This empty child is currently necessary to force the drop traget to appear
1488                    // despite us setting a min width above.
1489                    .child("")
1490                    .h_full()
1491                    .flex_grow()
1492                    .drag_over::<DraggedTab>(|bar| {
1493                        bar.bg(cx.theme().colors().drop_target_background)
1494                    })
1495                    .drag_over::<ProjectEntryId>(|bar| {
1496                        bar.bg(cx.theme().colors().drop_target_background)
1497                    })
1498                    .on_drop(cx.listener(move |this, dragged_tab: &DraggedTab, cx| {
1499                        this.drag_split_direction = None;
1500                        this.handle_tab_drop(dragged_tab, this.items.len(), cx)
1501                    }))
1502                    .on_drop(cx.listener(move |this, entry_id: &ProjectEntryId, cx| {
1503                        this.drag_split_direction = None;
1504                        this.handle_project_entry_drop(entry_id, cx)
1505                    }))
1506                    .on_drop(cx.listener(move |this, paths, cx| {
1507                        this.drag_split_direction = None;
1508                        this.handle_external_paths_drop(paths, cx)
1509                    })),
1510            )
1511    }
1512
1513    fn render_menu_overlay(menu: &View<ContextMenu>) -> Div {
1514        div()
1515            .absolute()
1516            .z_index(1)
1517            .bottom_0()
1518            .right_0()
1519            .size_0()
1520            .child(overlay().anchor(AnchorCorner::TopRight).child(menu.clone()))
1521    }
1522
1523    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1524        let mut tab_details = self.items.iter().map(|_| 0).collect::<Vec<_>>();
1525
1526        let mut tab_descriptions = HashMap::default();
1527        let mut done = false;
1528        while !done {
1529            done = true;
1530
1531            // Store item indices by their tab description.
1532            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1533                if let Some(description) = item.tab_description(*detail, cx) {
1534                    if *detail == 0
1535                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1536                    {
1537                        tab_descriptions
1538                            .entry(description)
1539                            .or_insert(Vec::new())
1540                            .push(ix);
1541                    }
1542                }
1543            }
1544
1545            // If two or more items have the same tab description, increase eir level
1546            // of detail and try again.
1547            for (_, item_ixs) in tab_descriptions.drain() {
1548                if item_ixs.len() > 1 {
1549                    done = false;
1550                    for ix in item_ixs {
1551                        tab_details[ix] += 1;
1552                    }
1553                }
1554            }
1555        }
1556
1557        tab_details
1558    }
1559
1560    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1561        self.zoomed = zoomed;
1562        cx.notify();
1563    }
1564
1565    pub fn is_zoomed(&self) -> bool {
1566        self.zoomed
1567    }
1568
1569    fn handle_drag_move<T>(&mut self, event: &DragMoveEvent<T>, cx: &mut ViewContext<Self>) {
1570        if !self.can_split {
1571            return;
1572        }
1573
1574        let edge_width = cx.rem_size() * 8;
1575        let cursor = event.event.position;
1576        let direction = if cursor.x < event.bounds.left() + edge_width {
1577            Some(SplitDirection::Left)
1578        } else if cursor.x > event.bounds.right() - edge_width {
1579            Some(SplitDirection::Right)
1580        } else if cursor.y < event.bounds.top() + edge_width {
1581            Some(SplitDirection::Up)
1582        } else if cursor.y > event.bounds.bottom() - edge_width {
1583            Some(SplitDirection::Down)
1584        } else {
1585            None
1586        };
1587
1588        if direction != self.drag_split_direction {
1589            self.drag_split_direction = direction;
1590        }
1591    }
1592
1593    fn handle_tab_drop(
1594        &mut self,
1595        dragged_tab: &DraggedTab,
1596        ix: usize,
1597        cx: &mut ViewContext<'_, Self>,
1598    ) {
1599        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
1600            if let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, cx) {
1601                return;
1602            }
1603        }
1604        let mut to_pane = cx.view().clone();
1605        let split_direction = self.drag_split_direction;
1606        let item_id = dragged_tab.item.item_id();
1607        let from_pane = dragged_tab.pane.clone();
1608        self.workspace
1609            .update(cx, |_, cx| {
1610                cx.defer(move |workspace, cx| {
1611                    if let Some(split_direction) = split_direction {
1612                        to_pane = workspace.split_pane(to_pane, split_direction, cx);
1613                    }
1614                    workspace.move_item(from_pane, to_pane, item_id, ix, cx);
1615                });
1616            })
1617            .log_err();
1618    }
1619
1620    fn handle_project_entry_drop(
1621        &mut self,
1622        project_entry_id: &ProjectEntryId,
1623        cx: &mut ViewContext<'_, Self>,
1624    ) {
1625        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
1626            if let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, cx) {
1627                return;
1628            }
1629        }
1630        let mut to_pane = cx.view().clone();
1631        let split_direction = self.drag_split_direction;
1632        let project_entry_id = *project_entry_id;
1633        self.workspace
1634            .update(cx, |_, cx| {
1635                cx.defer(move |workspace, cx| {
1636                    if let Some(path) = workspace
1637                        .project()
1638                        .read(cx)
1639                        .path_for_entry(project_entry_id, cx)
1640                    {
1641                        if let Some(split_direction) = split_direction {
1642                            to_pane = workspace.split_pane(to_pane, split_direction, cx);
1643                        }
1644                        workspace
1645                            .open_path(path, Some(to_pane.downgrade()), true, cx)
1646                            .detach_and_log_err(cx);
1647                    }
1648                });
1649            })
1650            .log_err();
1651    }
1652
1653    fn handle_external_paths_drop(
1654        &mut self,
1655        paths: &ExternalPaths,
1656        cx: &mut ViewContext<'_, Self>,
1657    ) {
1658        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
1659            if let ControlFlow::Break(()) = custom_drop_handle(self, paths, cx) {
1660                return;
1661            }
1662        }
1663        let mut to_pane = cx.view().clone();
1664        let mut split_direction = self.drag_split_direction;
1665        let paths = paths.paths().to_vec();
1666        self.workspace
1667            .update(cx, |workspace, cx| {
1668                let fs = Arc::clone(workspace.project().read(cx).fs());
1669                cx.spawn(|workspace, mut cx| async move {
1670                    let mut is_file_checks = FuturesUnordered::new();
1671                    for path in &paths {
1672                        is_file_checks.push(fs.is_file(path))
1673                    }
1674                    let mut has_files_to_open = false;
1675                    while let Some(is_file) = is_file_checks.next().await {
1676                        if is_file {
1677                            has_files_to_open = true;
1678                            break;
1679                        }
1680                    }
1681                    drop(is_file_checks);
1682                    if !has_files_to_open {
1683                        split_direction = None;
1684                    }
1685
1686                    if let Some(open_task) = workspace
1687                        .update(&mut cx, |workspace, cx| {
1688                            if let Some(split_direction) = split_direction {
1689                                to_pane = workspace.split_pane(to_pane, split_direction, cx);
1690                            }
1691                            workspace.open_paths(
1692                                paths,
1693                                OpenVisible::OnlyDirectories,
1694                                Some(to_pane.downgrade()),
1695                                cx,
1696                            )
1697                        })
1698                        .ok()
1699                    {
1700                        let _opened_items: Vec<_> = open_task.await;
1701                    }
1702                })
1703                .detach();
1704            })
1705            .log_err();
1706    }
1707
1708    pub fn display_nav_history_buttons(&mut self, display: bool) {
1709        self.display_nav_history_buttons = display;
1710    }
1711}
1712
1713impl FocusableView for Pane {
1714    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1715        self.focus_handle.clone()
1716    }
1717}
1718
1719impl Render for Pane {
1720    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1721        v_flex()
1722            .key_context("Pane")
1723            .track_focus(&self.focus_handle)
1724            .size_full()
1725            .flex_none()
1726            .overflow_hidden()
1727            .on_action(cx.listener(|pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx)))
1728            .on_action(cx.listener(|pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)))
1729            .on_action(
1730                cx.listener(|pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)),
1731            )
1732            .on_action(cx.listener(|pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)))
1733            .on_action(cx.listener(|pane, _: &GoBack, cx| pane.navigate_backward(cx)))
1734            .on_action(cx.listener(|pane, _: &GoForward, cx| pane.navigate_forward(cx)))
1735            .on_action(cx.listener(Pane::toggle_zoom))
1736            .on_action(cx.listener(|pane: &mut Pane, action: &ActivateItem, cx| {
1737                pane.activate_item(action.0, true, true, cx);
1738            }))
1739            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateLastItem, cx| {
1740                pane.activate_item(pane.items.len() - 1, true, true, cx);
1741            }))
1742            .on_action(cx.listener(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
1743                pane.activate_prev_item(true, cx);
1744            }))
1745            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateNextItem, cx| {
1746                pane.activate_next_item(true, cx);
1747            }))
1748            .on_action(
1749                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1750                    pane.close_active_item(action, cx)
1751                        .map(|task| task.detach_and_log_err(cx));
1752                }),
1753            )
1754            .on_action(
1755                cx.listener(|pane: &mut Self, action: &CloseInactiveItems, cx| {
1756                    pane.close_inactive_items(action, cx)
1757                        .map(|task| task.detach_and_log_err(cx));
1758                }),
1759            )
1760            .on_action(
1761                cx.listener(|pane: &mut Self, action: &CloseCleanItems, cx| {
1762                    pane.close_clean_items(action, cx)
1763                        .map(|task| task.detach_and_log_err(cx));
1764                }),
1765            )
1766            .on_action(
1767                cx.listener(|pane: &mut Self, action: &CloseItemsToTheLeft, cx| {
1768                    pane.close_items_to_the_left(action, cx)
1769                        .map(|task| task.detach_and_log_err(cx));
1770                }),
1771            )
1772            .on_action(
1773                cx.listener(|pane: &mut Self, action: &CloseItemsToTheRight, cx| {
1774                    pane.close_items_to_the_right(action, cx)
1775                        .map(|task| task.detach_and_log_err(cx));
1776                }),
1777            )
1778            .on_action(cx.listener(|pane: &mut Self, action: &CloseAllItems, cx| {
1779                pane.close_all_items(action, cx)
1780                    .map(|task| task.detach_and_log_err(cx));
1781            }))
1782            .on_action(
1783                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1784                    pane.close_active_item(action, cx)
1785                        .map(|task| task.detach_and_log_err(cx));
1786                }),
1787            )
1788            .on_action(
1789                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, cx| {
1790                    pane.project.update(cx, |_, cx| {
1791                        cx.emit(project::Event::RevealInProjectPanel(
1792                            ProjectEntryId::from_proto(action.entry_id),
1793                        ))
1794                    })
1795                }),
1796            )
1797            .when(self.active_item().is_some(), |pane| {
1798                pane.child(self.render_tab_bar(cx))
1799            })
1800            .child({
1801                let has_worktrees = self.project.read(cx).worktrees().next().is_some();
1802                // main content
1803                div()
1804                    .flex_1()
1805                    .relative()
1806                    .group("")
1807                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
1808                    .on_drag_move::<ProjectEntryId>(cx.listener(Self::handle_drag_move))
1809                    .on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
1810                    .map(|div| {
1811                        if let Some(item) = self.active_item() {
1812                            div.v_flex()
1813                                .child(self.toolbar.clone())
1814                                .child(item.to_any())
1815                        } else {
1816                            let placeholder = div.h_flex().size_full().justify_center();
1817                            if has_worktrees {
1818                                placeholder
1819                            } else {
1820                                placeholder.child(
1821                                    Label::new("Open a file or project to get started.")
1822                                        .color(Color::Muted),
1823                                )
1824                            }
1825                        }
1826                    })
1827                    .child(
1828                        // drag target
1829                        div()
1830                            .z_index(1)
1831                            .invisible()
1832                            .absolute()
1833                            .bg(theme::color_alpha(
1834                                cx.theme().colors().drop_target_background,
1835                                0.75,
1836                            ))
1837                            .group_drag_over::<DraggedTab>("", |style| style.visible())
1838                            .group_drag_over::<ProjectEntryId>("", |style| style.visible())
1839                            .group_drag_over::<ExternalPaths>("", |style| style.visible())
1840                            .when_some(self.can_drop_predicate.clone(), |this, p| {
1841                                this.can_drop(move |a, cx| p(a, cx))
1842                            })
1843                            .on_drop(cx.listener(move |this, dragged_tab, cx| {
1844                                this.handle_tab_drop(dragged_tab, this.active_item_index(), cx)
1845                            }))
1846                            .on_drop(cx.listener(move |this, entry_id, cx| {
1847                                this.handle_project_entry_drop(entry_id, cx)
1848                            }))
1849                            .on_drop(cx.listener(move |this, paths, cx| {
1850                                this.handle_external_paths_drop(paths, cx)
1851                            }))
1852                            .map(|div| match self.drag_split_direction {
1853                                None => div.top_0().left_0().right_0().bottom_0(),
1854                                Some(SplitDirection::Up) => div.top_0().left_0().right_0().h_32(),
1855                                Some(SplitDirection::Down) => {
1856                                    div.left_0().bottom_0().right_0().h_32()
1857                                }
1858                                Some(SplitDirection::Left) => {
1859                                    div.top_0().left_0().bottom_0().w_32()
1860                                }
1861                                Some(SplitDirection::Right) => {
1862                                    div.top_0().bottom_0().right_0().w_32()
1863                                }
1864                            }),
1865                    )
1866            })
1867            .on_mouse_down(
1868                MouseButton::Navigate(NavigationDirection::Back),
1869                cx.listener(|pane, _, cx| {
1870                    if let Some(workspace) = pane.workspace.upgrade() {
1871                        let pane = cx.view().downgrade();
1872                        cx.window_context().defer(move |cx| {
1873                            workspace.update(cx, |workspace, cx| {
1874                                workspace.go_back(pane, cx).detach_and_log_err(cx)
1875                            })
1876                        })
1877                    }
1878                }),
1879            )
1880            .on_mouse_down(
1881                MouseButton::Navigate(NavigationDirection::Forward),
1882                cx.listener(|pane, _, cx| {
1883                    if let Some(workspace) = pane.workspace.upgrade() {
1884                        let pane = cx.view().downgrade();
1885                        cx.window_context().defer(move |cx| {
1886                            workspace.update(cx, |workspace, cx| {
1887                                workspace.go_forward(pane, cx).detach_and_log_err(cx)
1888                            })
1889                        })
1890                    }
1891                }),
1892            )
1893    }
1894}
1895
1896impl ItemNavHistory {
1897    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
1898        self.history.push(data, self.item.clone(), cx);
1899    }
1900
1901    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1902        self.history.pop(NavigationMode::GoingBack, cx)
1903    }
1904
1905    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1906        self.history.pop(NavigationMode::GoingForward, cx)
1907    }
1908}
1909
1910impl NavHistory {
1911    pub fn for_each_entry(
1912        &self,
1913        cx: &AppContext,
1914        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
1915    ) {
1916        let borrowed_history = self.0.lock();
1917        borrowed_history
1918            .forward_stack
1919            .iter()
1920            .chain(borrowed_history.backward_stack.iter())
1921            .chain(borrowed_history.closed_stack.iter())
1922            .for_each(|entry| {
1923                if let Some(project_and_abs_path) =
1924                    borrowed_history.paths_by_item.get(&entry.item.id())
1925                {
1926                    f(entry, project_and_abs_path.clone());
1927                } else if let Some(item) = entry.item.upgrade() {
1928                    if let Some(path) = item.project_path(cx) {
1929                        f(entry, (path, None));
1930                    }
1931                }
1932            })
1933    }
1934
1935    pub fn set_mode(&mut self, mode: NavigationMode) {
1936        self.0.lock().mode = mode;
1937    }
1938
1939    pub fn mode(&self) -> NavigationMode {
1940        self.0.lock().mode
1941    }
1942
1943    pub fn disable(&mut self) {
1944        self.0.lock().mode = NavigationMode::Disabled;
1945    }
1946
1947    pub fn enable(&mut self) {
1948        self.0.lock().mode = NavigationMode::Normal;
1949    }
1950
1951    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
1952        let mut state = self.0.lock();
1953        let entry = match mode {
1954            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1955                return None
1956            }
1957            NavigationMode::GoingBack => &mut state.backward_stack,
1958            NavigationMode::GoingForward => &mut state.forward_stack,
1959            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
1960        }
1961        .pop_back();
1962        if entry.is_some() {
1963            state.did_update(cx);
1964        }
1965        entry
1966    }
1967
1968    pub fn push<D: 'static + Send + Any>(
1969        &mut self,
1970        data: Option<D>,
1971        item: Arc<dyn WeakItemHandle>,
1972        cx: &mut WindowContext,
1973    ) {
1974        let state = &mut *self.0.lock();
1975        match state.mode {
1976            NavigationMode::Disabled => {}
1977            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1978                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1979                    state.backward_stack.pop_front();
1980                }
1981                state.backward_stack.push_back(NavigationEntry {
1982                    item,
1983                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
1984                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
1985                });
1986                state.forward_stack.clear();
1987            }
1988            NavigationMode::GoingBack => {
1989                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1990                    state.forward_stack.pop_front();
1991                }
1992                state.forward_stack.push_back(NavigationEntry {
1993                    item,
1994                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
1995                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
1996                });
1997            }
1998            NavigationMode::GoingForward => {
1999                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2000                    state.backward_stack.pop_front();
2001                }
2002                state.backward_stack.push_back(NavigationEntry {
2003                    item,
2004                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2005                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2006                });
2007            }
2008            NavigationMode::ClosingItem => {
2009                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2010                    state.closed_stack.pop_front();
2011                }
2012                state.closed_stack.push_back(NavigationEntry {
2013                    item,
2014                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2015                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2016                });
2017            }
2018        }
2019        state.did_update(cx);
2020    }
2021
2022    pub fn remove_item(&mut self, item_id: EntityId) {
2023        let mut state = self.0.lock();
2024        state.paths_by_item.remove(&item_id);
2025        state
2026            .backward_stack
2027            .retain(|entry| entry.item.id() != item_id);
2028        state
2029            .forward_stack
2030            .retain(|entry| entry.item.id() != item_id);
2031        state
2032            .closed_stack
2033            .retain(|entry| entry.item.id() != item_id);
2034    }
2035
2036    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2037        self.0.lock().paths_by_item.get(&item_id).cloned()
2038    }
2039}
2040
2041impl NavHistoryState {
2042    pub fn did_update(&self, cx: &mut WindowContext) {
2043        if let Some(pane) = self.pane.upgrade() {
2044            cx.defer(move |cx| {
2045                pane.update(cx, |pane, cx| pane.history_updated(cx));
2046            });
2047        }
2048    }
2049}
2050
2051fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2052    let path = buffer_path
2053        .as_ref()
2054        .and_then(|p| p.path.to_str())
2055        .unwrap_or(&"This buffer");
2056    let path = truncate_and_remove_front(path, 80);
2057    format!("{path} contains unsaved edits. Do you want to save it?")
2058}
2059
2060#[cfg(test)]
2061mod tests {
2062    use super::*;
2063    use crate::item::test::{TestItem, TestProjectItem};
2064    use gpui::{TestAppContext, VisualTestContext};
2065    use project::FakeFs;
2066    use settings::SettingsStore;
2067    use theme::LoadThemes;
2068
2069    #[gpui::test]
2070    async fn test_remove_active_empty(cx: &mut TestAppContext) {
2071        init_test(cx);
2072        let fs = FakeFs::new(cx.executor());
2073
2074        let project = Project::test(fs, None, cx).await;
2075        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2076        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2077
2078        pane.update(cx, |pane, cx| {
2079            assert!(pane
2080                .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2081                .is_none())
2082        });
2083    }
2084
2085    #[gpui::test]
2086    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2087        init_test(cx);
2088        let fs = FakeFs::new(cx.executor());
2089
2090        let project = Project::test(fs, None, cx).await;
2091        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2092        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2093
2094        // 1. Add with a destination index
2095        //   a. Add before the active item
2096        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2097        pane.update(cx, |pane, cx| {
2098            pane.add_item(
2099                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2100                false,
2101                false,
2102                Some(0),
2103                cx,
2104            );
2105        });
2106        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2107
2108        //   b. Add after the active item
2109        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2110        pane.update(cx, |pane, cx| {
2111            pane.add_item(
2112                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2113                false,
2114                false,
2115                Some(2),
2116                cx,
2117            );
2118        });
2119        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2120
2121        //   c. Add at the end of the item list (including off the length)
2122        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2123        pane.update(cx, |pane, cx| {
2124            pane.add_item(
2125                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2126                false,
2127                false,
2128                Some(5),
2129                cx,
2130            );
2131        });
2132        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2133
2134        // 2. Add without a destination index
2135        //   a. Add with active item at the start of the item list
2136        set_labeled_items(&pane, ["A*", "B", "C"], cx);
2137        pane.update(cx, |pane, cx| {
2138            pane.add_item(
2139                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2140                false,
2141                false,
2142                None,
2143                cx,
2144            );
2145        });
2146        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2147
2148        //   b. Add with active item at the end of the item list
2149        set_labeled_items(&pane, ["A", "B", "C*"], cx);
2150        pane.update(cx, |pane, cx| {
2151            pane.add_item(
2152                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2153                false,
2154                false,
2155                None,
2156                cx,
2157            );
2158        });
2159        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2160    }
2161
2162    #[gpui::test]
2163    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2164        init_test(cx);
2165        let fs = FakeFs::new(cx.executor());
2166
2167        let project = Project::test(fs, None, cx).await;
2168        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2169        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2170
2171        // 1. Add with a destination index
2172        //   1a. Add before the active item
2173        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2174        pane.update(cx, |pane, cx| {
2175            pane.add_item(d, false, false, Some(0), cx);
2176        });
2177        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2178
2179        //   1b. Add after the active item
2180        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2181        pane.update(cx, |pane, cx| {
2182            pane.add_item(d, false, false, Some(2), cx);
2183        });
2184        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2185
2186        //   1c. Add at the end of the item list (including off the length)
2187        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2188        pane.update(cx, |pane, cx| {
2189            pane.add_item(a, false, false, Some(5), cx);
2190        });
2191        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2192
2193        //   1d. Add same item to active index
2194        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2195        pane.update(cx, |pane, cx| {
2196            pane.add_item(b, false, false, Some(1), cx);
2197        });
2198        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2199
2200        //   1e. Add item to index after same item in last position
2201        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2202        pane.update(cx, |pane, cx| {
2203            pane.add_item(c, false, false, Some(2), cx);
2204        });
2205        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2206
2207        // 2. Add without a destination index
2208        //   2a. Add with active item at the start of the item list
2209        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2210        pane.update(cx, |pane, cx| {
2211            pane.add_item(d, false, false, None, cx);
2212        });
2213        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2214
2215        //   2b. Add with active item at the end of the item list
2216        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2217        pane.update(cx, |pane, cx| {
2218            pane.add_item(a, false, false, None, cx);
2219        });
2220        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2221
2222        //   2c. Add active item to active item at end of list
2223        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2224        pane.update(cx, |pane, cx| {
2225            pane.add_item(c, false, false, None, cx);
2226        });
2227        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2228
2229        //   2d. Add active item to active item at start of list
2230        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2231        pane.update(cx, |pane, cx| {
2232            pane.add_item(a, false, false, None, cx);
2233        });
2234        assert_item_labels(&pane, ["A*", "B", "C"], cx);
2235    }
2236
2237    #[gpui::test]
2238    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2239        init_test(cx);
2240        let fs = FakeFs::new(cx.executor());
2241
2242        let project = Project::test(fs, None, cx).await;
2243        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2244        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2245
2246        // singleton view
2247        pane.update(cx, |pane, cx| {
2248            pane.add_item(
2249                Box::new(cx.new_view(|cx| {
2250                    TestItem::new(cx)
2251                        .with_singleton(true)
2252                        .with_label("buffer 1")
2253                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
2254                })),
2255                false,
2256                false,
2257                None,
2258                cx,
2259            );
2260        });
2261        assert_item_labels(&pane, ["buffer 1*"], cx);
2262
2263        // new singleton view with the same project entry
2264        pane.update(cx, |pane, cx| {
2265            pane.add_item(
2266                Box::new(cx.new_view(|cx| {
2267                    TestItem::new(cx)
2268                        .with_singleton(true)
2269                        .with_label("buffer 1")
2270                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2271                })),
2272                false,
2273                false,
2274                None,
2275                cx,
2276            );
2277        });
2278        assert_item_labels(&pane, ["buffer 1*"], cx);
2279
2280        // new singleton view with different project entry
2281        pane.update(cx, |pane, cx| {
2282            pane.add_item(
2283                Box::new(cx.new_view(|cx| {
2284                    TestItem::new(cx)
2285                        .with_singleton(true)
2286                        .with_label("buffer 2")
2287                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
2288                })),
2289                false,
2290                false,
2291                None,
2292                cx,
2293            );
2294        });
2295        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2296
2297        // new multibuffer view with the same project entry
2298        pane.update(cx, |pane, cx| {
2299            pane.add_item(
2300                Box::new(cx.new_view(|cx| {
2301                    TestItem::new(cx)
2302                        .with_singleton(false)
2303                        .with_label("multibuffer 1")
2304                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2305                })),
2306                false,
2307                false,
2308                None,
2309                cx,
2310            );
2311        });
2312        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2313
2314        // another multibuffer view with the same project entry
2315        pane.update(cx, |pane, cx| {
2316            pane.add_item(
2317                Box::new(cx.new_view(|cx| {
2318                    TestItem::new(cx)
2319                        .with_singleton(false)
2320                        .with_label("multibuffer 1b")
2321                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2322                })),
2323                false,
2324                false,
2325                None,
2326                cx,
2327            );
2328        });
2329        assert_item_labels(
2330            &pane,
2331            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2332            cx,
2333        );
2334    }
2335
2336    #[gpui::test]
2337    async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2338        init_test(cx);
2339        let fs = FakeFs::new(cx.executor());
2340
2341        let project = Project::test(fs, None, cx).await;
2342        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2343        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2344
2345        add_labeled_item(&pane, "A", false, cx);
2346        add_labeled_item(&pane, "B", false, cx);
2347        add_labeled_item(&pane, "C", false, cx);
2348        add_labeled_item(&pane, "D", false, cx);
2349        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2350
2351        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2352        add_labeled_item(&pane, "1", false, cx);
2353        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2354
2355        pane.update(cx, |pane, cx| {
2356            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2357        })
2358        .unwrap()
2359        .await
2360        .unwrap();
2361        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2362
2363        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2364        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2365
2366        pane.update(cx, |pane, cx| {
2367            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2368        })
2369        .unwrap()
2370        .await
2371        .unwrap();
2372        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2373
2374        pane.update(cx, |pane, cx| {
2375            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2376        })
2377        .unwrap()
2378        .await
2379        .unwrap();
2380        assert_item_labels(&pane, ["A", "C*"], cx);
2381
2382        pane.update(cx, |pane, cx| {
2383            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2384        })
2385        .unwrap()
2386        .await
2387        .unwrap();
2388        assert_item_labels(&pane, ["A*"], cx);
2389    }
2390
2391    #[gpui::test]
2392    async fn test_close_inactive_items(cx: &mut TestAppContext) {
2393        init_test(cx);
2394        let fs = FakeFs::new(cx.executor());
2395
2396        let project = Project::test(fs, None, cx).await;
2397        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2398        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2399
2400        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2401
2402        pane.update(cx, |pane, cx| {
2403            pane.close_inactive_items(&CloseInactiveItems, cx)
2404        })
2405        .unwrap()
2406        .await
2407        .unwrap();
2408        assert_item_labels(&pane, ["C*"], cx);
2409    }
2410
2411    #[gpui::test]
2412    async fn test_close_clean_items(cx: &mut TestAppContext) {
2413        init_test(cx);
2414        let fs = FakeFs::new(cx.executor());
2415
2416        let project = Project::test(fs, None, cx).await;
2417        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2418        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2419
2420        add_labeled_item(&pane, "A", true, cx);
2421        add_labeled_item(&pane, "B", false, cx);
2422        add_labeled_item(&pane, "C", true, cx);
2423        add_labeled_item(&pane, "D", false, cx);
2424        add_labeled_item(&pane, "E", false, cx);
2425        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2426
2427        pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2428            .unwrap()
2429            .await
2430            .unwrap();
2431        assert_item_labels(&pane, ["A^", "C*^"], cx);
2432    }
2433
2434    #[gpui::test]
2435    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2436        init_test(cx);
2437        let fs = FakeFs::new(cx.executor());
2438
2439        let project = Project::test(fs, None, cx).await;
2440        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2441        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2442
2443        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2444
2445        pane.update(cx, |pane, cx| {
2446            pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2447        })
2448        .unwrap()
2449        .await
2450        .unwrap();
2451        assert_item_labels(&pane, ["C*", "D", "E"], cx);
2452    }
2453
2454    #[gpui::test]
2455    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2456        init_test(cx);
2457        let fs = FakeFs::new(cx.executor());
2458
2459        let project = Project::test(fs, None, cx).await;
2460        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2461        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2462
2463        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2464
2465        pane.update(cx, |pane, cx| {
2466            pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2467        })
2468        .unwrap()
2469        .await
2470        .unwrap();
2471        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2472    }
2473
2474    #[gpui::test]
2475    async fn test_close_all_items(cx: &mut TestAppContext) {
2476        init_test(cx);
2477        let fs = FakeFs::new(cx.executor());
2478
2479        let project = Project::test(fs, None, cx).await;
2480        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2481        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2482
2483        add_labeled_item(&pane, "A", false, cx);
2484        add_labeled_item(&pane, "B", false, cx);
2485        add_labeled_item(&pane, "C", false, cx);
2486        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2487
2488        pane.update(cx, |pane, cx| {
2489            pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2490        })
2491        .unwrap()
2492        .await
2493        .unwrap();
2494        assert_item_labels(&pane, [], cx);
2495
2496        add_labeled_item(&pane, "A", true, cx);
2497        add_labeled_item(&pane, "B", true, cx);
2498        add_labeled_item(&pane, "C", true, cx);
2499        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2500
2501        let save = pane
2502            .update(cx, |pane, cx| {
2503                pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2504            })
2505            .unwrap();
2506
2507        cx.executor().run_until_parked();
2508        cx.simulate_prompt_answer(2);
2509        save.await.unwrap();
2510        assert_item_labels(&pane, [], cx);
2511    }
2512
2513    fn init_test(cx: &mut TestAppContext) {
2514        cx.update(|cx| {
2515            let settings_store = SettingsStore::test(cx);
2516            cx.set_global(settings_store);
2517            theme::init(LoadThemes::JustBase, cx);
2518            crate::init_settings(cx);
2519            Project::init_settings(cx);
2520        });
2521    }
2522
2523    fn add_labeled_item(
2524        pane: &View<Pane>,
2525        label: &str,
2526        is_dirty: bool,
2527        cx: &mut VisualTestContext,
2528    ) -> Box<View<TestItem>> {
2529        pane.update(cx, |pane, cx| {
2530            let labeled_item = Box::new(
2531                cx.new_view(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)),
2532            );
2533            pane.add_item(labeled_item.clone(), false, false, None, cx);
2534            labeled_item
2535        })
2536    }
2537
2538    fn set_labeled_items<const COUNT: usize>(
2539        pane: &View<Pane>,
2540        labels: [&str; COUNT],
2541        cx: &mut VisualTestContext,
2542    ) -> [Box<View<TestItem>>; COUNT] {
2543        pane.update(cx, |pane, cx| {
2544            pane.items.clear();
2545            let mut active_item_index = 0;
2546
2547            let mut index = 0;
2548            let items = labels.map(|mut label| {
2549                if label.ends_with("*") {
2550                    label = label.trim_end_matches("*");
2551                    active_item_index = index;
2552                }
2553
2554                let labeled_item = Box::new(cx.new_view(|cx| TestItem::new(cx).with_label(label)));
2555                pane.add_item(labeled_item.clone(), false, false, None, cx);
2556                index += 1;
2557                labeled_item
2558            });
2559
2560            pane.activate_item(active_item_index, false, false, cx);
2561
2562            items
2563        })
2564    }
2565
2566    // Assert the item label, with the active item label suffixed with a '*'
2567    fn assert_item_labels<const COUNT: usize>(
2568        pane: &View<Pane>,
2569        expected_states: [&str; COUNT],
2570        cx: &mut VisualTestContext,
2571    ) {
2572        pane.update(cx, |pane, cx| {
2573            let actual_states = pane
2574                .items
2575                .iter()
2576                .enumerate()
2577                .map(|(ix, item)| {
2578                    let mut state = item
2579                        .to_any()
2580                        .downcast::<TestItem>()
2581                        .unwrap()
2582                        .read(cx)
2583                        .label
2584                        .clone();
2585                    if ix == pane.active_item_index {
2586                        state.push('*');
2587                    }
2588                    if item.is_dirty(cx) {
2589                        state.push('^');
2590                    }
2591                    state
2592                })
2593                .collect::<Vec<_>>();
2594
2595            assert_eq!(
2596                actual_states, expected_states,
2597                "pane items do not match expectation"
2598            );
2599        })
2600    }
2601}
2602
2603impl Render for DraggedTab {
2604    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2605        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
2606        let label = self.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}