pane.rs

   1mod dragged_item_receiver;
   2
   3use super::{ItemHandle, SplitDirection};
   4pub use crate::toolbar::Toolbar;
   5use crate::{
   6    item::WeakItemHandle, notify_of_new_dock, AutosaveSetting, Item, NewCenterTerminal, NewFile,
   7    NewSearch, ToggleZoom, Workspace, WorkspaceSettings,
   8};
   9use anyhow::Result;
  10use collections::{HashMap, HashSet, VecDeque};
  11use context_menu::{ContextMenu, ContextMenuItem};
  12use drag_and_drop::{DragAndDrop, Draggable};
  13use dragged_item_receiver::dragged_item_receiver;
  14use futures::StreamExt;
  15use gpui::{
  16    actions,
  17    elements::*,
  18    geometry::{
  19        rect::RectF,
  20        vector::{vec2f, Vector2F},
  21    },
  22    impl_actions,
  23    keymap_matcher::KeymapContext,
  24    platform::{CursorStyle, MouseButton, NavigationDirection, PromptLevel},
  25    Action, AnyViewHandle, AnyWeakViewHandle, AppContext, AsyncAppContext, Entity, EventContext,
  26    LayoutContext, ModelHandle, MouseRegion, Quad, Task, View, ViewContext, ViewHandle,
  27    WeakViewHandle, WindowContext,
  28};
  29use project::{Project, ProjectEntryId, ProjectPath};
  30use serde::Deserialize;
  31use std::{
  32    any::Any,
  33    cell::RefCell,
  34    cmp, mem,
  35    path::{Path, PathBuf},
  36    rc::Rc,
  37    sync::{
  38        atomic::{AtomicUsize, Ordering},
  39        Arc,
  40    },
  41};
  42use theme::{Theme, ThemeSettings};
  43
  44#[derive(Clone, Deserialize, PartialEq)]
  45pub struct ActivateItem(pub usize);
  46
  47#[derive(Clone, PartialEq)]
  48pub struct CloseItemById {
  49    pub item_id: usize,
  50    pub pane: WeakViewHandle<Pane>,
  51}
  52
  53#[derive(Clone, PartialEq)]
  54pub struct CloseItemsToTheLeftById {
  55    pub item_id: usize,
  56    pub pane: WeakViewHandle<Pane>,
  57}
  58
  59#[derive(Clone, PartialEq)]
  60pub struct CloseItemsToTheRightById {
  61    pub item_id: usize,
  62    pub pane: WeakViewHandle<Pane>,
  63}
  64
  65actions!(
  66    pane,
  67    [
  68        ActivatePrevItem,
  69        ActivateNextItem,
  70        ActivateLastItem,
  71        CloseActiveItem,
  72        CloseInactiveItems,
  73        CloseCleanItems,
  74        CloseItemsToTheLeft,
  75        CloseItemsToTheRight,
  76        CloseAllItems,
  77        GoBack,
  78        GoForward,
  79        ReopenClosedItem,
  80        SplitLeft,
  81        SplitUp,
  82        SplitRight,
  83        SplitDown,
  84    ]
  85);
  86
  87impl_actions!(pane, [ActivateItem]);
  88
  89const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
  90
  91pub type BackgroundActions = fn() -> &'static [(&'static str, &'static dyn Action)];
  92
  93pub fn init(cx: &mut AppContext) {
  94    cx.add_action(Pane::toggle_zoom);
  95    cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
  96        pane.activate_item(action.0, true, true, cx);
  97    });
  98    cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
  99        pane.activate_item(pane.items.len() - 1, true, true, cx);
 100    });
 101    cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
 102        pane.activate_prev_item(true, cx);
 103    });
 104    cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
 105        pane.activate_next_item(true, cx);
 106    });
 107    cx.add_async_action(Pane::close_active_item);
 108    cx.add_async_action(Pane::close_inactive_items);
 109    cx.add_async_action(Pane::close_clean_items);
 110    cx.add_async_action(Pane::close_items_to_the_left);
 111    cx.add_async_action(Pane::close_items_to_the_right);
 112    cx.add_async_action(Pane::close_all_items);
 113    cx.add_action(|pane: &mut Pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx));
 114    cx.add_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx));
 115    cx.add_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx));
 116    cx.add_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx));
 117}
 118
 119#[derive(Debug)]
 120pub enum Event {
 121    AddItem { item: Box<dyn ItemHandle> },
 122    ActivateItem { local: bool },
 123    Remove,
 124    RemoveItem { item_id: usize },
 125    Split(SplitDirection),
 126    ChangeItemTitle,
 127    Focus,
 128    ZoomIn,
 129    ZoomOut,
 130}
 131
 132pub struct Pane {
 133    items: Vec<Box<dyn ItemHandle>>,
 134    activation_history: Vec<usize>,
 135    zoomed: bool,
 136    active_item_index: usize,
 137    last_focused_view_by_item: HashMap<usize, AnyWeakViewHandle>,
 138    autoscroll: bool,
 139    nav_history: NavHistory,
 140    toolbar: ViewHandle<Toolbar>,
 141    tab_bar_context_menu: TabBarContextMenu,
 142    tab_context_menu: ViewHandle<ContextMenu>,
 143    _background_actions: BackgroundActions,
 144    workspace: WeakViewHandle<Workspace>,
 145    project: ModelHandle<Project>,
 146    has_focus: bool,
 147    can_drop: Rc<dyn Fn(&DragAndDrop<Workspace>, &WindowContext) -> bool>,
 148    can_split: bool,
 149    render_tab_bar_buttons: Rc<dyn Fn(&mut Pane, &mut ViewContext<Pane>) -> AnyElement<Pane>>,
 150}
 151
 152pub struct ItemNavHistory {
 153    history: NavHistory,
 154    item: Rc<dyn WeakItemHandle>,
 155}
 156
 157#[derive(Clone)]
 158pub struct NavHistory(Rc<RefCell<NavHistoryState>>);
 159
 160struct NavHistoryState {
 161    mode: NavigationMode,
 162    backward_stack: VecDeque<NavigationEntry>,
 163    forward_stack: VecDeque<NavigationEntry>,
 164    closed_stack: VecDeque<NavigationEntry>,
 165    paths_by_item: HashMap<usize, (ProjectPath, Option<PathBuf>)>,
 166    pane: WeakViewHandle<Pane>,
 167    next_timestamp: Arc<AtomicUsize>,
 168}
 169
 170#[derive(Copy, Clone)]
 171pub enum NavigationMode {
 172    Normal,
 173    GoingBack,
 174    GoingForward,
 175    ClosingItem,
 176    ReopeningClosedItem,
 177    Disabled,
 178}
 179
 180impl Default for NavigationMode {
 181    fn default() -> Self {
 182        Self::Normal
 183    }
 184}
 185
 186pub struct NavigationEntry {
 187    pub item: Rc<dyn WeakItemHandle>,
 188    pub data: Option<Box<dyn Any>>,
 189    pub timestamp: usize,
 190}
 191
 192pub struct DraggedItem {
 193    pub handle: Box<dyn ItemHandle>,
 194    pub pane: WeakViewHandle<Pane>,
 195}
 196
 197pub enum ReorderBehavior {
 198    None,
 199    MoveAfterActive,
 200    MoveToIndex(usize),
 201}
 202
 203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 204enum TabBarContextMenuKind {
 205    New,
 206    Split,
 207}
 208
 209struct TabBarContextMenu {
 210    kind: TabBarContextMenuKind,
 211    handle: ViewHandle<ContextMenu>,
 212}
 213
 214impl TabBarContextMenu {
 215    fn handle_if_kind(&self, kind: TabBarContextMenuKind) -> Option<ViewHandle<ContextMenu>> {
 216        if self.kind == kind {
 217            return Some(self.handle.clone());
 218        }
 219        None
 220    }
 221}
 222
 223impl Pane {
 224    pub fn new(
 225        workspace: WeakViewHandle<Workspace>,
 226        project: ModelHandle<Project>,
 227        background_actions: BackgroundActions,
 228        next_timestamp: Arc<AtomicUsize>,
 229        cx: &mut ViewContext<Self>,
 230    ) -> Self {
 231        let pane_view_id = cx.view_id();
 232        let handle = cx.weak_handle();
 233        let context_menu = cx.add_view(|cx| ContextMenu::new(pane_view_id, cx));
 234        context_menu.update(cx, |menu, _| {
 235            menu.set_position_mode(OverlayPositionMode::Local)
 236        });
 237
 238        Self {
 239            items: Vec::new(),
 240            activation_history: Vec::new(),
 241            zoomed: false,
 242            active_item_index: 0,
 243            last_focused_view_by_item: Default::default(),
 244            autoscroll: false,
 245            nav_history: NavHistory(Rc::new(RefCell::new(NavHistoryState {
 246                mode: NavigationMode::Normal,
 247                backward_stack: Default::default(),
 248                forward_stack: Default::default(),
 249                closed_stack: Default::default(),
 250                paths_by_item: Default::default(),
 251                pane: handle.clone(),
 252                next_timestamp,
 253            }))),
 254            toolbar: cx.add_view(|_| Toolbar::new(Some(handle))),
 255            tab_bar_context_menu: TabBarContextMenu {
 256                kind: TabBarContextMenuKind::New,
 257                handle: context_menu,
 258            },
 259            tab_context_menu: cx.add_view(|cx| ContextMenu::new(pane_view_id, cx)),
 260            _background_actions: background_actions,
 261            workspace,
 262            project,
 263            has_focus: false,
 264            can_drop: Rc::new(|_, _| true),
 265            can_split: true,
 266            render_tab_bar_buttons: Rc::new(|pane, cx| {
 267                Flex::row()
 268                    // New menu
 269                    .with_child(Self::render_tab_bar_button(
 270                        0,
 271                        "icons/plus_12.svg",
 272                        false,
 273                        Some(("New...".into(), None)),
 274                        cx,
 275                        |pane, cx| pane.deploy_new_menu(cx),
 276                        pane.tab_bar_context_menu
 277                            .handle_if_kind(TabBarContextMenuKind::New),
 278                    ))
 279                    .with_child(Self::render_tab_bar_button(
 280                        1,
 281                        "icons/split_12.svg",
 282                        false,
 283                        Some(("Split Pane".into(), None)),
 284                        cx,
 285                        |pane, cx| pane.deploy_split_menu(cx),
 286                        pane.tab_bar_context_menu
 287                            .handle_if_kind(TabBarContextMenuKind::Split),
 288                    ))
 289                    .with_child({
 290                        let icon_path;
 291                        let tooltip_label;
 292                        if pane.is_zoomed() {
 293                            icon_path = "icons/minimize_8.svg";
 294                            tooltip_label = "Zoom In".into();
 295                        } else {
 296                            icon_path = "icons/maximize_8.svg";
 297                            tooltip_label = "Zoom In".into();
 298                        }
 299
 300                        Pane::render_tab_bar_button(
 301                            2,
 302                            icon_path,
 303                            pane.is_zoomed(),
 304                            Some((tooltip_label, Some(Box::new(ToggleZoom)))),
 305                            cx,
 306                            move |pane, cx| pane.toggle_zoom(&Default::default(), cx),
 307                            None,
 308                        )
 309                    })
 310                    .into_any()
 311            }),
 312        }
 313    }
 314
 315    pub(crate) fn workspace(&self) -> &WeakViewHandle<Workspace> {
 316        &self.workspace
 317    }
 318
 319    pub fn has_focus(&self) -> bool {
 320        self.has_focus
 321    }
 322
 323    pub fn active_item_index(&self) -> usize {
 324        self.active_item_index
 325    }
 326
 327    pub fn on_can_drop<F>(&mut self, can_drop: F)
 328    where
 329        F: 'static + Fn(&DragAndDrop<Workspace>, &WindowContext) -> bool,
 330    {
 331        self.can_drop = Rc::new(can_drop);
 332    }
 333
 334    pub fn set_can_split(&mut self, can_split: bool, cx: &mut ViewContext<Self>) {
 335        self.can_split = can_split;
 336        cx.notify();
 337    }
 338
 339    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
 340        self.toolbar.update(cx, |toolbar, cx| {
 341            toolbar.set_can_navigate(can_navigate, cx);
 342        });
 343        cx.notify();
 344    }
 345
 346    pub fn set_render_tab_bar_buttons<F>(&mut self, cx: &mut ViewContext<Self>, render: F)
 347    where
 348        F: 'static + Fn(&mut Pane, &mut ViewContext<Pane>) -> AnyElement<Pane>,
 349    {
 350        self.render_tab_bar_buttons = Rc::new(render);
 351        cx.notify();
 352    }
 353
 354    pub fn nav_history_for_item<T: Item>(&self, item: &ViewHandle<T>) -> ItemNavHistory {
 355        ItemNavHistory {
 356            history: self.nav_history.clone(),
 357            item: Rc::new(item.downgrade()),
 358        }
 359    }
 360
 361    pub fn nav_history(&self) -> &NavHistory {
 362        &self.nav_history
 363    }
 364
 365    pub fn nav_history_mut(&mut self) -> &mut NavHistory {
 366        &mut self.nav_history
 367    }
 368
 369    pub fn disable_history(&mut self) {
 370        self.nav_history.disable();
 371    }
 372
 373    pub fn enable_history(&mut self) {
 374        self.nav_history.enable();
 375    }
 376
 377    pub fn can_navigate_backward(&self) -> bool {
 378        !self.nav_history.0.borrow().backward_stack.is_empty()
 379    }
 380
 381    pub fn can_navigate_forward(&self) -> bool {
 382        !self.nav_history.0.borrow().forward_stack.is_empty()
 383    }
 384
 385    fn history_updated(&mut self, cx: &mut ViewContext<Self>) {
 386        self.toolbar.update(cx, |_, cx| cx.notify());
 387    }
 388
 389    pub(crate) fn open_item(
 390        &mut self,
 391        project_entry_id: ProjectEntryId,
 392        focus_item: bool,
 393        cx: &mut ViewContext<Self>,
 394        build_item: impl FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
 395    ) -> Box<dyn ItemHandle> {
 396        let mut existing_item = None;
 397        for (index, item) in self.items.iter().enumerate() {
 398            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [project_entry_id]
 399            {
 400                let item = item.boxed_clone();
 401                existing_item = Some((index, item));
 402                break;
 403            }
 404        }
 405
 406        if let Some((index, existing_item)) = existing_item {
 407            self.activate_item(index, focus_item, focus_item, cx);
 408            existing_item
 409        } else {
 410            let new_item = build_item(cx);
 411            self.add_item(new_item.clone(), true, focus_item, None, cx);
 412            new_item
 413        }
 414    }
 415
 416    pub fn add_item(
 417        &mut self,
 418        item: Box<dyn ItemHandle>,
 419        activate_pane: bool,
 420        focus_item: bool,
 421        destination_index: Option<usize>,
 422        cx: &mut ViewContext<Self>,
 423    ) {
 424        if item.is_singleton(cx) {
 425            if let Some(&entry_id) = item.project_entry_ids(cx).get(0) {
 426                let project = self.project.read(cx);
 427                if let Some(project_path) = project.path_for_entry(entry_id, cx) {
 428                    let abs_path = project.absolute_path(&project_path, cx);
 429                    self.nav_history
 430                        .0
 431                        .borrow_mut()
 432                        .paths_by_item
 433                        .insert(item.id(), (project_path, abs_path));
 434                }
 435            }
 436        }
 437        // If no destination index is specified, add or move the item after the active item.
 438        let mut insertion_index = {
 439            cmp::min(
 440                if let Some(destination_index) = destination_index {
 441                    destination_index
 442                } else {
 443                    self.active_item_index + 1
 444                },
 445                self.items.len(),
 446            )
 447        };
 448
 449        // Does the item already exist?
 450        let project_entry_id = if item.is_singleton(cx) {
 451            item.project_entry_ids(cx).get(0).copied()
 452        } else {
 453            None
 454        };
 455
 456        let existing_item_index = self.items.iter().position(|existing_item| {
 457            if existing_item.id() == item.id() {
 458                true
 459            } else if existing_item.is_singleton(cx) {
 460                existing_item
 461                    .project_entry_ids(cx)
 462                    .get(0)
 463                    .map_or(false, |existing_entry_id| {
 464                        Some(existing_entry_id) == project_entry_id.as_ref()
 465                    })
 466            } else {
 467                false
 468            }
 469        });
 470
 471        if let Some(existing_item_index) = existing_item_index {
 472            // If the item already exists, move it to the desired destination and activate it
 473
 474            if existing_item_index != insertion_index {
 475                let existing_item_is_active = existing_item_index == self.active_item_index;
 476
 477                // If the caller didn't specify a destination and the added item is already
 478                // the active one, don't move it
 479                if existing_item_is_active && destination_index.is_none() {
 480                    insertion_index = existing_item_index;
 481                } else {
 482                    self.items.remove(existing_item_index);
 483                    if existing_item_index < self.active_item_index {
 484                        self.active_item_index -= 1;
 485                    }
 486                    insertion_index = insertion_index.min(self.items.len());
 487
 488                    self.items.insert(insertion_index, item.clone());
 489
 490                    if existing_item_is_active {
 491                        self.active_item_index = insertion_index;
 492                    } else if insertion_index <= self.active_item_index {
 493                        self.active_item_index += 1;
 494                    }
 495                }
 496
 497                cx.notify();
 498            }
 499
 500            self.activate_item(insertion_index, activate_pane, focus_item, cx);
 501        } else {
 502            self.items.insert(insertion_index, item.clone());
 503            if insertion_index <= self.active_item_index {
 504                self.active_item_index += 1;
 505            }
 506
 507            self.activate_item(insertion_index, activate_pane, focus_item, cx);
 508            cx.notify();
 509        }
 510
 511        cx.emit(Event::AddItem { item });
 512    }
 513
 514    pub fn items_len(&self) -> usize {
 515        self.items.len()
 516    }
 517
 518    pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> + DoubleEndedIterator {
 519        self.items.iter()
 520    }
 521
 522    pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
 523        self.items
 524            .iter()
 525            .filter_map(|item| item.as_any().clone().downcast())
 526    }
 527
 528    pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
 529        self.items.get(self.active_item_index).cloned()
 530    }
 531
 532    pub fn item_for_entry(
 533        &self,
 534        entry_id: ProjectEntryId,
 535        cx: &AppContext,
 536    ) -> Option<Box<dyn ItemHandle>> {
 537        self.items.iter().find_map(|item| {
 538            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
 539                Some(item.boxed_clone())
 540            } else {
 541                None
 542            }
 543        })
 544    }
 545
 546    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
 547        self.items.iter().position(|i| i.id() == item.id())
 548    }
 549
 550    pub fn toggle_zoom(&mut self, _: &ToggleZoom, cx: &mut ViewContext<Self>) {
 551        // Potentially warn the user of the new keybinding
 552        let workspace_handle = self.workspace().clone();
 553        cx.spawn(|_, mut cx| async move { notify_of_new_dock(&workspace_handle, &mut cx) })
 554            .detach();
 555
 556        if self.zoomed {
 557            cx.emit(Event::ZoomOut);
 558        } else if !self.items.is_empty() {
 559            if !self.has_focus {
 560                cx.focus_self();
 561            }
 562            cx.emit(Event::ZoomIn);
 563        }
 564    }
 565
 566    pub fn activate_item(
 567        &mut self,
 568        index: usize,
 569        activate_pane: bool,
 570        focus_item: bool,
 571        cx: &mut ViewContext<Self>,
 572    ) {
 573        use NavigationMode::{GoingBack, GoingForward};
 574
 575        if index < self.items.len() {
 576            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
 577            if prev_active_item_ix != self.active_item_index
 578                || matches!(self.nav_history.mode(), GoingBack | GoingForward)
 579            {
 580                if let Some(prev_item) = self.items.get(prev_active_item_ix) {
 581                    prev_item.deactivated(cx);
 582                }
 583
 584                cx.emit(Event::ActivateItem {
 585                    local: activate_pane,
 586                });
 587            }
 588
 589            if let Some(newly_active_item) = self.items.get(index) {
 590                self.activation_history
 591                    .retain(|&previously_active_item_id| {
 592                        previously_active_item_id != newly_active_item.id()
 593                    });
 594                self.activation_history.push(newly_active_item.id());
 595            }
 596
 597            self.update_toolbar(cx);
 598
 599            if focus_item {
 600                self.focus_active_item(cx);
 601            }
 602
 603            self.autoscroll = true;
 604            cx.notify();
 605        }
 606    }
 607
 608    pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
 609        let mut index = self.active_item_index;
 610        if index > 0 {
 611            index -= 1;
 612        } else if !self.items.is_empty() {
 613            index = self.items.len() - 1;
 614        }
 615        self.activate_item(index, activate_pane, activate_pane, cx);
 616    }
 617
 618    pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
 619        let mut index = self.active_item_index;
 620        if index + 1 < self.items.len() {
 621            index += 1;
 622        } else {
 623            index = 0;
 624        }
 625        self.activate_item(index, activate_pane, activate_pane, cx);
 626    }
 627
 628    pub fn close_active_item(
 629        &mut self,
 630        _: &CloseActiveItem,
 631        cx: &mut ViewContext<Self>,
 632    ) -> Option<Task<Result<()>>> {
 633        if self.items.is_empty() {
 634            return None;
 635        }
 636        let active_item_id = self.items[self.active_item_index].id();
 637        Some(self.close_item_by_id(active_item_id, cx))
 638    }
 639
 640    pub fn close_item_by_id(
 641        &mut self,
 642        item_id_to_close: usize,
 643        cx: &mut ViewContext<Self>,
 644    ) -> Task<Result<()>> {
 645        self.close_items(cx, move |view_id| view_id == item_id_to_close)
 646    }
 647
 648    pub fn close_inactive_items(
 649        &mut self,
 650        _: &CloseInactiveItems,
 651        cx: &mut ViewContext<Self>,
 652    ) -> Option<Task<Result<()>>> {
 653        if self.items.is_empty() {
 654            return None;
 655        }
 656
 657        let active_item_id = self.items[self.active_item_index].id();
 658        Some(self.close_items(cx, move |item_id| item_id != active_item_id))
 659    }
 660
 661    pub fn close_clean_items(
 662        &mut self,
 663        _: &CloseCleanItems,
 664        cx: &mut ViewContext<Self>,
 665    ) -> Option<Task<Result<()>>> {
 666        let item_ids: Vec<_> = self
 667            .items()
 668            .filter(|item| !item.is_dirty(cx))
 669            .map(|item| item.id())
 670            .collect();
 671        Some(self.close_items(cx, move |item_id| item_ids.contains(&item_id)))
 672    }
 673
 674    pub fn close_items_to_the_left(
 675        &mut self,
 676        _: &CloseItemsToTheLeft,
 677        cx: &mut ViewContext<Self>,
 678    ) -> Option<Task<Result<()>>> {
 679        if self.items.is_empty() {
 680            return None;
 681        }
 682        let active_item_id = self.items[self.active_item_index].id();
 683        Some(self.close_items_to_the_left_by_id(active_item_id, cx))
 684    }
 685
 686    pub fn close_items_to_the_left_by_id(
 687        &mut self,
 688        item_id: usize,
 689        cx: &mut ViewContext<Self>,
 690    ) -> Task<Result<()>> {
 691        let item_ids: Vec<_> = self
 692            .items()
 693            .take_while(|item| item.id() != item_id)
 694            .map(|item| item.id())
 695            .collect();
 696        self.close_items(cx, move |item_id| item_ids.contains(&item_id))
 697    }
 698
 699    pub fn close_items_to_the_right(
 700        &mut self,
 701        _: &CloseItemsToTheRight,
 702        cx: &mut ViewContext<Self>,
 703    ) -> Option<Task<Result<()>>> {
 704        if self.items.is_empty() {
 705            return None;
 706        }
 707        let active_item_id = self.items[self.active_item_index].id();
 708        Some(self.close_items_to_the_right_by_id(active_item_id, cx))
 709    }
 710
 711    pub fn close_items_to_the_right_by_id(
 712        &mut self,
 713        item_id: usize,
 714        cx: &mut ViewContext<Self>,
 715    ) -> Task<Result<()>> {
 716        let item_ids: Vec<_> = self
 717            .items()
 718            .rev()
 719            .take_while(|item| item.id() != item_id)
 720            .map(|item| item.id())
 721            .collect();
 722        self.close_items(cx, move |item_id| item_ids.contains(&item_id))
 723    }
 724
 725    pub fn close_all_items(
 726        &mut self,
 727        _: &CloseAllItems,
 728        cx: &mut ViewContext<Self>,
 729    ) -> Option<Task<Result<()>>> {
 730        Some(self.close_items(cx, move |_| true))
 731    }
 732
 733    pub fn close_items(
 734        &mut self,
 735        cx: &mut ViewContext<Pane>,
 736        should_close: impl 'static + Fn(usize) -> bool,
 737    ) -> Task<Result<()>> {
 738        // Find the items to close.
 739        let mut items_to_close = Vec::new();
 740        for item in &self.items {
 741            if should_close(item.id()) {
 742                items_to_close.push(item.boxed_clone());
 743            }
 744        }
 745
 746        // If a buffer is open both in a singleton editor and in a multibuffer, make sure
 747        // to focus the singleton buffer when prompting to save that buffer, as opposed
 748        // to focusing the multibuffer, because this gives the user a more clear idea
 749        // of what content they would be saving.
 750        items_to_close.sort_by_key(|item| !item.is_singleton(cx));
 751
 752        let workspace = self.workspace.clone();
 753        cx.spawn(|pane, mut cx| async move {
 754            let mut saved_project_items_ids = HashSet::default();
 755            for item in items_to_close.clone() {
 756                // Find the item's current index and its set of project item models. Avoid
 757                // storing these in advance, in case they have changed since this task
 758                // was started.
 759                let (item_ix, mut project_item_ids) = pane.read_with(&cx, |pane, cx| {
 760                    (pane.index_for_item(&*item), item.project_item_model_ids(cx))
 761                })?;
 762                let item_ix = if let Some(ix) = item_ix {
 763                    ix
 764                } else {
 765                    continue;
 766                };
 767
 768                // Check if this view has any project items that are not open anywhere else
 769                // in the workspace, AND that the user has not already been prompted to save.
 770                // If there are any such project entries, prompt the user to save this item.
 771                let project = workspace.read_with(&cx, |workspace, cx| {
 772                    for item in workspace.items(cx) {
 773                        if !items_to_close
 774                            .iter()
 775                            .any(|item_to_close| item_to_close.id() == item.id())
 776                        {
 777                            let other_project_item_ids = item.project_item_model_ids(cx);
 778                            project_item_ids.retain(|id| !other_project_item_ids.contains(id));
 779                        }
 780                    }
 781                    workspace.project().clone()
 782                })?;
 783                let should_save = project_item_ids
 784                    .iter()
 785                    .any(|id| saved_project_items_ids.insert(*id));
 786
 787                if should_save
 788                    && !Self::save_item(project.clone(), &pane, item_ix, &*item, true, &mut cx)
 789                        .await?
 790                {
 791                    break;
 792                }
 793
 794                // Remove the item from the pane.
 795                pane.update(&mut cx, |pane, cx| {
 796                    if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
 797                        pane.remove_item(item_ix, false, cx);
 798                    }
 799                })?;
 800            }
 801
 802            pane.update(&mut cx, |_, cx| cx.notify())?;
 803            Ok(())
 804        })
 805    }
 806
 807    pub fn remove_item(
 808        &mut self,
 809        item_index: usize,
 810        activate_pane: bool,
 811        cx: &mut ViewContext<Self>,
 812    ) {
 813        self.activation_history
 814            .retain(|&history_entry| history_entry != self.items[item_index].id());
 815
 816        if item_index == self.active_item_index {
 817            let index_to_activate = self
 818                .activation_history
 819                .pop()
 820                .and_then(|last_activated_item| {
 821                    self.items.iter().enumerate().find_map(|(index, item)| {
 822                        (item.id() == last_activated_item).then_some(index)
 823                    })
 824                })
 825                // We didn't have a valid activation history entry, so fallback
 826                // to activating the item to the left
 827                .unwrap_or_else(|| item_index.min(self.items.len()).saturating_sub(1));
 828
 829            let should_activate = activate_pane || self.has_focus;
 830            self.activate_item(index_to_activate, should_activate, should_activate, cx);
 831        }
 832
 833        let item = self.items.remove(item_index);
 834
 835        cx.emit(Event::RemoveItem { item_id: item.id() });
 836        if self.items.is_empty() {
 837            item.deactivated(cx);
 838            self.update_toolbar(cx);
 839            cx.emit(Event::Remove);
 840        }
 841
 842        if item_index < self.active_item_index {
 843            self.active_item_index -= 1;
 844        }
 845
 846        self.nav_history.set_mode(NavigationMode::ClosingItem);
 847        item.deactivated(cx);
 848        self.nav_history.set_mode(NavigationMode::Normal);
 849
 850        if let Some(path) = item.project_path(cx) {
 851            let abs_path = self
 852                .nav_history
 853                .0
 854                .borrow()
 855                .paths_by_item
 856                .get(&item.id())
 857                .and_then(|(_, abs_path)| abs_path.clone());
 858            self.nav_history
 859                .0
 860                .borrow_mut()
 861                .paths_by_item
 862                .insert(item.id(), (path, abs_path));
 863        } else {
 864            self.nav_history
 865                .0
 866                .borrow_mut()
 867                .paths_by_item
 868                .remove(&item.id());
 869        }
 870
 871        if self.items.is_empty() && self.zoomed {
 872            cx.emit(Event::ZoomOut);
 873        }
 874
 875        cx.notify();
 876    }
 877
 878    pub async fn save_item(
 879        project: ModelHandle<Project>,
 880        pane: &WeakViewHandle<Pane>,
 881        item_ix: usize,
 882        item: &dyn ItemHandle,
 883        should_prompt_for_save: bool,
 884        cx: &mut AsyncAppContext,
 885    ) -> Result<bool> {
 886        const CONFLICT_MESSAGE: &str =
 887            "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 888        const DIRTY_MESSAGE: &str = "This file contains unsaved edits. Do you want to save it?";
 889
 890        let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
 891            (
 892                item.has_conflict(cx),
 893                item.is_dirty(cx),
 894                item.can_save(cx),
 895                item.is_singleton(cx),
 896            )
 897        });
 898
 899        if has_conflict && can_save {
 900            let mut answer = pane.update(cx, |pane, cx| {
 901                pane.activate_item(item_ix, true, true, cx);
 902                cx.prompt(
 903                    PromptLevel::Warning,
 904                    CONFLICT_MESSAGE,
 905                    &["Overwrite", "Discard", "Cancel"],
 906                )
 907            })?;
 908            match answer.next().await {
 909                Some(0) => pane.update(cx, |_, cx| item.save(project, cx))?.await?,
 910                Some(1) => pane.update(cx, |_, cx| item.reload(project, cx))?.await?,
 911                _ => return Ok(false),
 912            }
 913        } else if is_dirty && (can_save || is_singleton) {
 914            let will_autosave = cx.read(|cx| {
 915                matches!(
 916                    settings::get::<WorkspaceSettings>(cx).autosave,
 917                    AutosaveSetting::OnFocusChange | AutosaveSetting::OnWindowChange
 918                ) && Self::can_autosave_item(&*item, cx)
 919            });
 920            let should_save = if should_prompt_for_save && !will_autosave {
 921                let mut answer = pane.update(cx, |pane, cx| {
 922                    pane.activate_item(item_ix, true, true, cx);
 923                    cx.prompt(
 924                        PromptLevel::Warning,
 925                        DIRTY_MESSAGE,
 926                        &["Save", "Don't Save", "Cancel"],
 927                    )
 928                })?;
 929                match answer.next().await {
 930                    Some(0) => true,
 931                    Some(1) => false,
 932                    _ => return Ok(false),
 933                }
 934            } else {
 935                true
 936            };
 937
 938            if should_save {
 939                if can_save {
 940                    pane.update(cx, |_, cx| item.save(project, cx))?.await?;
 941                } else if is_singleton {
 942                    let start_abs_path = project
 943                        .read_with(cx, |project, cx| {
 944                            let worktree = project.visible_worktrees(cx).next()?;
 945                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 946                        })
 947                        .unwrap_or_else(|| Path::new("").into());
 948
 949                    let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
 950                    if let Some(abs_path) = abs_path.next().await.flatten() {
 951                        pane.update(cx, |_, cx| item.save_as(project, abs_path, cx))?
 952                            .await?;
 953                    } else {
 954                        return Ok(false);
 955                    }
 956                }
 957            }
 958        }
 959        Ok(true)
 960    }
 961
 962    fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
 963        let is_deleted = item.project_entry_ids(cx).is_empty();
 964        item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
 965    }
 966
 967    pub fn autosave_item(
 968        item: &dyn ItemHandle,
 969        project: ModelHandle<Project>,
 970        cx: &mut WindowContext,
 971    ) -> Task<Result<()>> {
 972        if Self::can_autosave_item(item, cx) {
 973            item.save(project, cx)
 974        } else {
 975            Task::ready(Ok(()))
 976        }
 977    }
 978
 979    pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
 980        if let Some(active_item) = self.active_item() {
 981            cx.focus(active_item.as_any());
 982        }
 983    }
 984
 985    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
 986        cx.emit(Event::Split(direction));
 987    }
 988
 989    fn deploy_split_menu(&mut self, cx: &mut ViewContext<Self>) {
 990        self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
 991            menu.show(
 992                Default::default(),
 993                AnchorCorner::TopRight,
 994                vec![
 995                    ContextMenuItem::action("Split Right", SplitRight),
 996                    ContextMenuItem::action("Split Left", SplitLeft),
 997                    ContextMenuItem::action("Split Up", SplitUp),
 998                    ContextMenuItem::action("Split Down", SplitDown),
 999                ],
1000                cx,
1001            );
1002        });
1003
1004        self.tab_bar_context_menu.kind = TabBarContextMenuKind::Split;
1005    }
1006
1007    fn deploy_new_menu(&mut self, cx: &mut ViewContext<Self>) {
1008        self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1009            menu.show(
1010                Default::default(),
1011                AnchorCorner::TopRight,
1012                vec![
1013                    ContextMenuItem::action("New File", NewFile),
1014                    ContextMenuItem::action("New Terminal", NewCenterTerminal),
1015                    ContextMenuItem::action("New Search", NewSearch),
1016                ],
1017                cx,
1018            );
1019        });
1020
1021        self.tab_bar_context_menu.kind = TabBarContextMenuKind::New;
1022    }
1023
1024    fn deploy_tab_context_menu(
1025        &mut self,
1026        position: Vector2F,
1027        target_item_id: usize,
1028        cx: &mut ViewContext<Self>,
1029    ) {
1030        let active_item_id = self.items[self.active_item_index].id();
1031        let is_active_item = target_item_id == active_item_id;
1032        let target_pane = cx.weak_handle();
1033
1034        // The `CloseInactiveItems` action should really be called "CloseOthers" and the behaviour should be dynamically based on the tab the action is ran on.  Currently, this is a weird action because you can run it on a non-active tab and it will close everything by the actual active tab
1035
1036        self.tab_context_menu.update(cx, |menu, cx| {
1037            menu.show(
1038                position,
1039                AnchorCorner::TopLeft,
1040                if is_active_item {
1041                    vec![
1042                        ContextMenuItem::action("Close Active Item", CloseActiveItem),
1043                        ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1044                        ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1045                        ContextMenuItem::action("Close Items To The Left", CloseItemsToTheLeft),
1046                        ContextMenuItem::action("Close Items To The Right", CloseItemsToTheRight),
1047                        ContextMenuItem::action("Close All Items", CloseAllItems),
1048                    ]
1049                } else {
1050                    // In the case of the user right clicking on a non-active tab, for some item-closing commands, we need to provide the id of the tab, for the others, we can reuse the existing command.
1051                    vec![
1052                        ContextMenuItem::handler("Close Inactive Item", {
1053                            let pane = target_pane.clone();
1054                            move |cx| {
1055                                if let Some(pane) = pane.upgrade(cx) {
1056                                    pane.update(cx, |pane, cx| {
1057                                        pane.close_item_by_id(target_item_id, cx)
1058                                            .detach_and_log_err(cx);
1059                                    })
1060                                }
1061                            }
1062                        }),
1063                        ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1064                        ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1065                        ContextMenuItem::handler("Close Items To The Left", {
1066                            let pane = target_pane.clone();
1067                            move |cx| {
1068                                if let Some(pane) = pane.upgrade(cx) {
1069                                    pane.update(cx, |pane, cx| {
1070                                        pane.close_items_to_the_left_by_id(target_item_id, cx)
1071                                            .detach_and_log_err(cx);
1072                                    })
1073                                }
1074                            }
1075                        }),
1076                        ContextMenuItem::handler("Close Items To The Right", {
1077                            let pane = target_pane.clone();
1078                            move |cx| {
1079                                if let Some(pane) = pane.upgrade(cx) {
1080                                    pane.update(cx, |pane, cx| {
1081                                        pane.close_items_to_the_right_by_id(target_item_id, cx)
1082                                            .detach_and_log_err(cx);
1083                                    })
1084                                }
1085                            }
1086                        }),
1087                        ContextMenuItem::action("Close All Items", CloseAllItems),
1088                    ]
1089                },
1090                cx,
1091            );
1092        });
1093    }
1094
1095    pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
1096        &self.toolbar
1097    }
1098
1099    pub fn handle_deleted_project_item(
1100        &mut self,
1101        entry_id: ProjectEntryId,
1102        cx: &mut ViewContext<Pane>,
1103    ) -> Option<()> {
1104        let (item_index_to_delete, item_id) = self.items().enumerate().find_map(|(i, item)| {
1105            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
1106                Some((i, item.id()))
1107            } else {
1108                None
1109            }
1110        })?;
1111
1112        self.remove_item(item_index_to_delete, false, cx);
1113        self.nav_history.remove_item(item_id);
1114
1115        Some(())
1116    }
1117
1118    fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1119        let active_item = self
1120            .items
1121            .get(self.active_item_index)
1122            .map(|item| item.as_ref());
1123        self.toolbar.update(cx, |toolbar, cx| {
1124            toolbar.set_active_item(active_item, cx);
1125        });
1126    }
1127
1128    fn render_tabs(&mut self, cx: &mut ViewContext<Self>) -> impl Element<Self> {
1129        let theme = theme::current(cx).clone();
1130
1131        let pane = cx.handle().downgrade();
1132        let autoscroll = if mem::take(&mut self.autoscroll) {
1133            Some(self.active_item_index)
1134        } else {
1135            None
1136        };
1137
1138        let pane_active = self.has_focus;
1139
1140        enum Tabs {}
1141        let mut row = Flex::row().scrollable::<Tabs>(1, autoscroll, cx);
1142        for (ix, (item, detail)) in self
1143            .items
1144            .iter()
1145            .cloned()
1146            .zip(self.tab_details(cx))
1147            .enumerate()
1148        {
1149            let detail = if detail == 0 { None } else { Some(detail) };
1150            let tab_active = ix == self.active_item_index;
1151
1152            row.add_child({
1153                enum TabDragReceiver {}
1154                let mut receiver =
1155                    dragged_item_receiver::<TabDragReceiver, _, _>(self, ix, ix, true, None, cx, {
1156                        let item = item.clone();
1157                        let pane = pane.clone();
1158                        let detail = detail.clone();
1159
1160                        let theme = theme::current(cx).clone();
1161                        let mut tooltip_theme = theme.tooltip.clone();
1162                        tooltip_theme.max_text_width = None;
1163                        let tab_tooltip_text =
1164                            item.tab_tooltip_text(cx).map(|text| text.into_owned());
1165
1166                        move |mouse_state, cx| {
1167                            let tab_style =
1168                                theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1169                            let hovered = mouse_state.hovered();
1170
1171                            enum Tab {}
1172                            let mouse_event_handler =
1173                                MouseEventHandler::<Tab, Pane>::new(ix, cx, |_, cx| {
1174                                    Self::render_tab(
1175                                        &item,
1176                                        pane.clone(),
1177                                        ix == 0,
1178                                        detail,
1179                                        hovered,
1180                                        tab_style,
1181                                        cx,
1182                                    )
1183                                })
1184                                .on_down(MouseButton::Left, move |_, this, cx| {
1185                                    this.activate_item(ix, true, true, cx);
1186                                })
1187                                .on_click(MouseButton::Middle, {
1188                                    let item_id = item.id();
1189                                    move |_, pane, cx| {
1190                                        pane.close_item_by_id(item_id, cx).detach_and_log_err(cx);
1191                                    }
1192                                })
1193                                .on_down(
1194                                    MouseButton::Right,
1195                                    move |event, pane, cx| {
1196                                        pane.deploy_tab_context_menu(event.position, item.id(), cx);
1197                                    },
1198                                );
1199
1200                            if let Some(tab_tooltip_text) = tab_tooltip_text {
1201                                mouse_event_handler
1202                                    .with_tooltip::<Self>(
1203                                        ix,
1204                                        tab_tooltip_text,
1205                                        None,
1206                                        tooltip_theme,
1207                                        cx,
1208                                    )
1209                                    .into_any()
1210                            } else {
1211                                mouse_event_handler.into_any()
1212                            }
1213                        }
1214                    });
1215
1216                if !pane_active || !tab_active {
1217                    receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1218                }
1219
1220                receiver.as_draggable(
1221                    DraggedItem {
1222                        handle: item,
1223                        pane: pane.clone(),
1224                    },
1225                    {
1226                        let theme = theme::current(cx).clone();
1227
1228                        let detail = detail.clone();
1229                        move |dragged_item: &DraggedItem, cx: &mut ViewContext<Workspace>| {
1230                            let tab_style = &theme.workspace.tab_bar.dragged_tab;
1231                            Self::render_dragged_tab(
1232                                &dragged_item.handle,
1233                                dragged_item.pane.clone(),
1234                                false,
1235                                detail,
1236                                false,
1237                                &tab_style,
1238                                cx,
1239                            )
1240                        }
1241                    },
1242                )
1243            })
1244        }
1245
1246        // Use the inactive tab style along with the current pane's active status to decide how to render
1247        // the filler
1248        let filler_index = self.items.len();
1249        let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1250        enum Filler {}
1251        row.add_child(
1252            dragged_item_receiver::<Filler, _, _>(self, 0, filler_index, true, None, cx, |_, _| {
1253                Empty::new()
1254                    .contained()
1255                    .with_style(filler_style.container)
1256                    .with_border(filler_style.container.border)
1257            })
1258            .flex(1., true)
1259            .into_any_named("filler"),
1260        );
1261
1262        row
1263    }
1264
1265    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1266        let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1267
1268        let mut tab_descriptions = HashMap::default();
1269        let mut done = false;
1270        while !done {
1271            done = true;
1272
1273            // Store item indices by their tab description.
1274            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1275                if let Some(description) = item.tab_description(*detail, cx) {
1276                    if *detail == 0
1277                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1278                    {
1279                        tab_descriptions
1280                            .entry(description)
1281                            .or_insert(Vec::new())
1282                            .push(ix);
1283                    }
1284                }
1285            }
1286
1287            // If two or more items have the same tab description, increase their level
1288            // of detail and try again.
1289            for (_, item_ixs) in tab_descriptions.drain() {
1290                if item_ixs.len() > 1 {
1291                    done = false;
1292                    for ix in item_ixs {
1293                        tab_details[ix] += 1;
1294                    }
1295                }
1296            }
1297        }
1298
1299        tab_details
1300    }
1301
1302    fn render_tab(
1303        item: &Box<dyn ItemHandle>,
1304        pane: WeakViewHandle<Pane>,
1305        first: bool,
1306        detail: Option<usize>,
1307        hovered: bool,
1308        tab_style: &theme::Tab,
1309        cx: &mut ViewContext<Self>,
1310    ) -> AnyElement<Self> {
1311        let title = item.tab_content(detail, &tab_style, cx);
1312        Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1313    }
1314
1315    fn render_dragged_tab(
1316        item: &Box<dyn ItemHandle>,
1317        pane: WeakViewHandle<Pane>,
1318        first: bool,
1319        detail: Option<usize>,
1320        hovered: bool,
1321        tab_style: &theme::Tab,
1322        cx: &mut ViewContext<Workspace>,
1323    ) -> AnyElement<Workspace> {
1324        let title = item.dragged_tab_content(detail, &tab_style, cx);
1325        Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1326    }
1327
1328    fn render_tab_with_title<T: View>(
1329        title: AnyElement<T>,
1330        item: &Box<dyn ItemHandle>,
1331        pane: WeakViewHandle<Pane>,
1332        first: bool,
1333        hovered: bool,
1334        tab_style: &theme::Tab,
1335        cx: &mut ViewContext<T>,
1336    ) -> AnyElement<T> {
1337        let mut container = tab_style.container.clone();
1338        if first {
1339            container.border.left = false;
1340        }
1341
1342        Flex::row()
1343            .with_child({
1344                let diameter = 7.0;
1345                let icon_color = if item.has_conflict(cx) {
1346                    Some(tab_style.icon_conflict)
1347                } else if item.is_dirty(cx) {
1348                    Some(tab_style.icon_dirty)
1349                } else {
1350                    None
1351                };
1352
1353                Canvas::new(move |scene, bounds, _, _, _| {
1354                    if let Some(color) = icon_color {
1355                        let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1356                        scene.push_quad(Quad {
1357                            bounds: square,
1358                            background: Some(color),
1359                            border: Default::default(),
1360                            corner_radius: diameter / 2.,
1361                        });
1362                    }
1363                })
1364                .constrained()
1365                .with_width(diameter)
1366                .with_height(diameter)
1367                .aligned()
1368            })
1369            .with_child(title.aligned().contained().with_style(ContainerStyle {
1370                margin: Margin {
1371                    left: tab_style.spacing,
1372                    right: tab_style.spacing,
1373                    ..Default::default()
1374                },
1375                ..Default::default()
1376            }))
1377            .with_child(
1378                if hovered {
1379                    let item_id = item.id();
1380                    enum TabCloseButton {}
1381                    let icon = Svg::new("icons/x_mark_8.svg");
1382                    MouseEventHandler::<TabCloseButton, _>::new(item_id, cx, |mouse_state, _| {
1383                        if mouse_state.hovered() {
1384                            icon.with_color(tab_style.icon_close_active)
1385                        } else {
1386                            icon.with_color(tab_style.icon_close)
1387                        }
1388                    })
1389                    .with_padding(Padding::uniform(4.))
1390                    .with_cursor_style(CursorStyle::PointingHand)
1391                    .on_click(MouseButton::Left, {
1392                        let pane = pane.clone();
1393                        move |_, _, cx| {
1394                            let pane = pane.clone();
1395                            cx.window_context().defer(move |cx| {
1396                                if let Some(pane) = pane.upgrade(cx) {
1397                                    pane.update(cx, |pane, cx| {
1398                                        pane.close_item_by_id(item_id, cx).detach_and_log_err(cx);
1399                                    });
1400                                }
1401                            });
1402                        }
1403                    })
1404                    .into_any_named("close-tab-icon")
1405                    .constrained()
1406                } else {
1407                    Empty::new().constrained()
1408                }
1409                .with_width(tab_style.close_icon_width)
1410                .aligned(),
1411            )
1412            .contained()
1413            .with_style(container)
1414            .constrained()
1415            .with_height(tab_style.height)
1416            .into_any()
1417    }
1418
1419    pub fn render_tab_bar_button<F: 'static + Fn(&mut Pane, &mut EventContext<Pane>)>(
1420        index: usize,
1421        icon: &'static str,
1422        is_active: bool,
1423        tooltip: Option<(String, Option<Box<dyn Action>>)>,
1424        cx: &mut ViewContext<Pane>,
1425        on_click: F,
1426        context_menu: Option<ViewHandle<ContextMenu>>,
1427    ) -> AnyElement<Pane> {
1428        enum TabBarButton {}
1429
1430        let mut button = MouseEventHandler::<TabBarButton, _>::new(index, cx, |mouse_state, cx| {
1431            let theme = &settings::get::<ThemeSettings>(cx).theme.workspace.tab_bar;
1432            let style = theme.pane_button.in_state(is_active).style_for(mouse_state);
1433            Svg::new(icon)
1434                .with_color(style.color)
1435                .constrained()
1436                .with_width(style.icon_width)
1437                .aligned()
1438                .constrained()
1439                .with_width(style.button_width)
1440                .with_height(style.button_width)
1441        })
1442        .with_cursor_style(CursorStyle::PointingHand)
1443        .on_click(MouseButton::Left, move |_, pane, cx| on_click(pane, cx))
1444        .into_any();
1445        if let Some((tooltip, action)) = tooltip {
1446            let tooltip_style = settings::get::<ThemeSettings>(cx).theme.tooltip.clone();
1447            button = button
1448                .with_tooltip::<TabBarButton>(index, tooltip, action, tooltip_style, cx)
1449                .into_any();
1450        }
1451
1452        Stack::new()
1453            .with_child(button)
1454            .with_children(
1455                context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right()),
1456            )
1457            .flex(1., false)
1458            .into_any_named("tab bar button")
1459    }
1460
1461    fn render_blank_pane(&self, theme: &Theme, _cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1462        let background = theme.workspace.background;
1463        Empty::new()
1464            .contained()
1465            .with_background_color(background)
1466            .into_any()
1467    }
1468
1469    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1470        self.zoomed = zoomed;
1471        cx.notify();
1472    }
1473
1474    pub fn is_zoomed(&self) -> bool {
1475        self.zoomed
1476    }
1477}
1478
1479impl Entity for Pane {
1480    type Event = Event;
1481}
1482
1483impl View for Pane {
1484    fn ui_name() -> &'static str {
1485        "Pane"
1486    }
1487
1488    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1489        enum MouseNavigationHandler {}
1490
1491        MouseEventHandler::<MouseNavigationHandler, _>::new(0, cx, |_, cx| {
1492            let active_item_index = self.active_item_index;
1493
1494            if let Some(active_item) = self.active_item() {
1495                Flex::column()
1496                    .with_child({
1497                        let theme = theme::current(cx).clone();
1498
1499                        let mut stack = Stack::new();
1500
1501                        enum TabBarEventHandler {}
1502                        stack.add_child(
1503                            MouseEventHandler::<TabBarEventHandler, _>::new(0, cx, |_, _| {
1504                                Empty::new()
1505                                    .contained()
1506                                    .with_style(theme.workspace.tab_bar.container)
1507                            })
1508                            .on_down(
1509                                MouseButton::Left,
1510                                move |_, this, cx| {
1511                                    this.activate_item(active_item_index, true, true, cx);
1512                                },
1513                            ),
1514                        );
1515
1516                        let mut tab_row = Flex::row()
1517                            .with_child(self.render_tabs(cx).flex(1., true).into_any_named("tabs"));
1518
1519                        if self.has_focus {
1520                            let render_tab_bar_buttons = self.render_tab_bar_buttons.clone();
1521                            tab_row.add_child(
1522                                (render_tab_bar_buttons)(self, cx)
1523                                    .contained()
1524                                    .with_style(theme.workspace.tab_bar.pane_button_container)
1525                                    .flex(1., false)
1526                                    .into_any(),
1527                            )
1528                        }
1529
1530                        stack.add_child(tab_row);
1531                        stack
1532                            .constrained()
1533                            .with_height(theme.workspace.tab_bar.height)
1534                            .flex(1., false)
1535                            .into_any_named("tab bar")
1536                    })
1537                    .with_child({
1538                        enum PaneContentTabDropTarget {}
1539                        dragged_item_receiver::<PaneContentTabDropTarget, _, _>(
1540                            self,
1541                            0,
1542                            self.active_item_index + 1,
1543                            !self.can_split,
1544                            if self.can_split { Some(100.) } else { None },
1545                            cx,
1546                            {
1547                                let toolbar = self.toolbar.clone();
1548                                let toolbar_hidden = toolbar.read(cx).hidden();
1549                                move |_, cx| {
1550                                    Flex::column()
1551                                        .with_children(
1552                                            (!toolbar_hidden)
1553                                                .then(|| ChildView::new(&toolbar, cx).expanded()),
1554                                        )
1555                                        .with_child(
1556                                            ChildView::new(active_item.as_any(), cx).flex(1., true),
1557                                        )
1558                                }
1559                            },
1560                        )
1561                        .flex(1., true)
1562                    })
1563                    .with_child(ChildView::new(&self.tab_context_menu, cx))
1564                    .into_any()
1565            } else {
1566                enum EmptyPane {}
1567                let theme = theme::current(cx).clone();
1568
1569                dragged_item_receiver::<EmptyPane, _, _>(self, 0, 0, false, None, cx, |_, cx| {
1570                    self.render_blank_pane(&theme, cx)
1571                })
1572                .on_down(MouseButton::Left, |_, _, cx| {
1573                    cx.focus_parent();
1574                })
1575                .into_any()
1576            }
1577        })
1578        .on_down(
1579            MouseButton::Navigate(NavigationDirection::Back),
1580            move |_, pane, cx| {
1581                if let Some(workspace) = pane.workspace.upgrade(cx) {
1582                    let pane = cx.weak_handle();
1583                    cx.window_context().defer(move |cx| {
1584                        workspace.update(cx, |workspace, cx| {
1585                            workspace.go_back(pane, cx).detach_and_log_err(cx)
1586                        })
1587                    })
1588                }
1589            },
1590        )
1591        .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1592            move |_, pane, cx| {
1593                if let Some(workspace) = pane.workspace.upgrade(cx) {
1594                    let pane = cx.weak_handle();
1595                    cx.window_context().defer(move |cx| {
1596                        workspace.update(cx, |workspace, cx| {
1597                            workspace.go_forward(pane, cx).detach_and_log_err(cx)
1598                        })
1599                    })
1600                }
1601            }
1602        })
1603        .into_any_named("pane")
1604    }
1605
1606    fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1607        if !self.has_focus {
1608            self.has_focus = true;
1609            cx.emit(Event::Focus);
1610            cx.notify();
1611        }
1612
1613        self.toolbar.update(cx, |toolbar, cx| {
1614            toolbar.focus_changed(true, cx);
1615        });
1616
1617        if let Some(active_item) = self.active_item() {
1618            if cx.is_self_focused() {
1619                // Pane was focused directly. We need to either focus a view inside the active item,
1620                // or focus the active item itself
1621                if let Some(weak_last_focused_view) =
1622                    self.last_focused_view_by_item.get(&active_item.id())
1623                {
1624                    if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1625                        cx.focus(&last_focused_view);
1626                        return;
1627                    } else {
1628                        self.last_focused_view_by_item.remove(&active_item.id());
1629                    }
1630                }
1631
1632                cx.focus(active_item.as_any());
1633            } else if focused != self.tab_bar_context_menu.handle {
1634                self.last_focused_view_by_item
1635                    .insert(active_item.id(), focused.downgrade());
1636            }
1637        }
1638    }
1639
1640    fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
1641        self.has_focus = false;
1642        self.toolbar.update(cx, |toolbar, cx| {
1643            toolbar.focus_changed(false, cx);
1644        });
1645        cx.notify();
1646    }
1647
1648    fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
1649        Self::reset_to_default_keymap_context(keymap);
1650    }
1651}
1652
1653impl ItemNavHistory {
1654    pub fn push<D: 'static + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
1655        self.history.push(data, self.item.clone(), cx);
1656    }
1657
1658    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1659        self.history.pop(NavigationMode::GoingBack, cx)
1660    }
1661
1662    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1663        self.history.pop(NavigationMode::GoingForward, cx)
1664    }
1665}
1666
1667impl NavHistory {
1668    pub fn for_each_entry(
1669        &self,
1670        cx: &AppContext,
1671        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
1672    ) {
1673        let borrowed_history = self.0.borrow();
1674        borrowed_history
1675            .forward_stack
1676            .iter()
1677            .chain(borrowed_history.backward_stack.iter())
1678            .chain(borrowed_history.closed_stack.iter())
1679            .for_each(|entry| {
1680                if let Some(project_and_abs_path) =
1681                    borrowed_history.paths_by_item.get(&entry.item.id())
1682                {
1683                    f(entry, project_and_abs_path.clone());
1684                } else if let Some(item) = entry.item.upgrade(cx) {
1685                    if let Some(path) = item.project_path(cx) {
1686                        f(entry, (path, None));
1687                    }
1688                }
1689            })
1690    }
1691
1692    pub fn set_mode(&mut self, mode: NavigationMode) {
1693        self.0.borrow_mut().mode = mode;
1694    }
1695
1696    pub fn mode(&self) -> NavigationMode {
1697        self.0.borrow().mode
1698    }
1699
1700    pub fn disable(&mut self) {
1701        self.0.borrow_mut().mode = NavigationMode::Disabled;
1702    }
1703
1704    pub fn enable(&mut self) {
1705        self.0.borrow_mut().mode = NavigationMode::Normal;
1706    }
1707
1708    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
1709        let mut state = self.0.borrow_mut();
1710        let entry = match mode {
1711            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1712                return None
1713            }
1714            NavigationMode::GoingBack => &mut state.backward_stack,
1715            NavigationMode::GoingForward => &mut state.forward_stack,
1716            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
1717        }
1718        .pop_back();
1719        if entry.is_some() {
1720            state.did_update(cx);
1721        }
1722        entry
1723    }
1724
1725    pub fn push<D: 'static + Any>(
1726        &mut self,
1727        data: Option<D>,
1728        item: Rc<dyn WeakItemHandle>,
1729        cx: &mut WindowContext,
1730    ) {
1731        let state = &mut *self.0.borrow_mut();
1732        match state.mode {
1733            NavigationMode::Disabled => {}
1734            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1735                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1736                    state.backward_stack.pop_front();
1737                }
1738                state.backward_stack.push_back(NavigationEntry {
1739                    item,
1740                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1741                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
1742                });
1743                state.forward_stack.clear();
1744            }
1745            NavigationMode::GoingBack => {
1746                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1747                    state.forward_stack.pop_front();
1748                }
1749                state.forward_stack.push_back(NavigationEntry {
1750                    item,
1751                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1752                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
1753                });
1754            }
1755            NavigationMode::GoingForward => {
1756                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1757                    state.backward_stack.pop_front();
1758                }
1759                state.backward_stack.push_back(NavigationEntry {
1760                    item,
1761                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1762                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
1763                });
1764            }
1765            NavigationMode::ClosingItem => {
1766                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1767                    state.closed_stack.pop_front();
1768                }
1769                state.closed_stack.push_back(NavigationEntry {
1770                    item,
1771                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1772                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
1773                });
1774            }
1775        }
1776        state.did_update(cx);
1777    }
1778
1779    pub fn remove_item(&mut self, item_id: usize) {
1780        let mut state = self.0.borrow_mut();
1781        state.paths_by_item.remove(&item_id);
1782        state
1783            .backward_stack
1784            .retain(|entry| entry.item.id() != item_id);
1785        state
1786            .forward_stack
1787            .retain(|entry| entry.item.id() != item_id);
1788        state
1789            .closed_stack
1790            .retain(|entry| entry.item.id() != item_id);
1791    }
1792
1793    pub fn path_for_item(&self, item_id: usize) -> Option<(ProjectPath, Option<PathBuf>)> {
1794        self.0.borrow().paths_by_item.get(&item_id).cloned()
1795    }
1796}
1797
1798impl NavHistoryState {
1799    pub fn did_update(&self, cx: &mut WindowContext) {
1800        if let Some(pane) = self.pane.upgrade(cx) {
1801            cx.defer(move |cx| {
1802                pane.update(cx, |pane, cx| pane.history_updated(cx));
1803            });
1804        }
1805    }
1806}
1807
1808pub struct PaneBackdrop<V: View> {
1809    child_view: usize,
1810    child: AnyElement<V>,
1811}
1812
1813impl<V: View> PaneBackdrop<V> {
1814    pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
1815        PaneBackdrop {
1816            child,
1817            child_view: pane_item_view,
1818        }
1819    }
1820}
1821
1822impl<V: View> Element<V> for PaneBackdrop<V> {
1823    type LayoutState = ();
1824
1825    type PaintState = ();
1826
1827    fn layout(
1828        &mut self,
1829        constraint: gpui::SizeConstraint,
1830        view: &mut V,
1831        cx: &mut LayoutContext<V>,
1832    ) -> (Vector2F, Self::LayoutState) {
1833        let size = self.child.layout(constraint, view, cx);
1834        (size, ())
1835    }
1836
1837    fn paint(
1838        &mut self,
1839        scene: &mut gpui::SceneBuilder,
1840        bounds: RectF,
1841        visible_bounds: RectF,
1842        _: &mut Self::LayoutState,
1843        view: &mut V,
1844        cx: &mut ViewContext<V>,
1845    ) -> Self::PaintState {
1846        let background = theme::current(cx).editor.background;
1847
1848        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
1849
1850        scene.push_quad(gpui::Quad {
1851            bounds: RectF::new(bounds.origin(), bounds.size()),
1852            background: Some(background),
1853            ..Default::default()
1854        });
1855
1856        let child_view_id = self.child_view;
1857        scene.push_mouse_region(
1858            MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
1859                gpui::platform::MouseButton::Left,
1860                move |_, _: &mut V, cx| {
1861                    let window_id = cx.window_id();
1862                    cx.app_context().focus(window_id, Some(child_view_id))
1863                },
1864            ),
1865        );
1866
1867        scene.paint_layer(Some(bounds), |scene| {
1868            self.child
1869                .paint(scene, bounds.origin(), visible_bounds, view, cx)
1870        })
1871    }
1872
1873    fn rect_for_text_range(
1874        &self,
1875        range_utf16: std::ops::Range<usize>,
1876        _bounds: RectF,
1877        _visible_bounds: RectF,
1878        _layout: &Self::LayoutState,
1879        _paint: &Self::PaintState,
1880        view: &V,
1881        cx: &gpui::ViewContext<V>,
1882    ) -> Option<RectF> {
1883        self.child.rect_for_text_range(range_utf16, view, cx)
1884    }
1885
1886    fn debug(
1887        &self,
1888        _bounds: RectF,
1889        _layout: &Self::LayoutState,
1890        _paint: &Self::PaintState,
1891        view: &V,
1892        cx: &gpui::ViewContext<V>,
1893    ) -> serde_json::Value {
1894        gpui::json::json!({
1895            "type": "Pane Back Drop",
1896            "view": self.child_view,
1897            "child": self.child.debug(view, cx),
1898        })
1899    }
1900}
1901
1902#[cfg(test)]
1903mod tests {
1904    use super::*;
1905    use crate::item::test::{TestItem, TestProjectItem};
1906    use gpui::TestAppContext;
1907    use project::FakeFs;
1908    use settings::SettingsStore;
1909
1910    #[gpui::test]
1911    async fn test_remove_active_empty(cx: &mut TestAppContext) {
1912        init_test(cx);
1913        let fs = FakeFs::new(cx.background());
1914
1915        let project = Project::test(fs, None, cx).await;
1916        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1917        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1918
1919        pane.update(cx, |pane, cx| {
1920            assert!(pane.close_active_item(&CloseActiveItem, cx).is_none())
1921        });
1922    }
1923
1924    #[gpui::test]
1925    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
1926        cx.foreground().forbid_parking();
1927        init_test(cx);
1928        let fs = FakeFs::new(cx.background());
1929
1930        let project = Project::test(fs, None, cx).await;
1931        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1932        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1933
1934        // 1. Add with a destination index
1935        //   a. Add before the active item
1936        set_labeled_items(&pane, ["A", "B*", "C"], cx);
1937        pane.update(cx, |pane, cx| {
1938            pane.add_item(
1939                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1940                false,
1941                false,
1942                Some(0),
1943                cx,
1944            );
1945        });
1946        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1947
1948        //   b. Add after the active item
1949        set_labeled_items(&pane, ["A", "B*", "C"], cx);
1950        pane.update(cx, |pane, cx| {
1951            pane.add_item(
1952                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1953                false,
1954                false,
1955                Some(2),
1956                cx,
1957            );
1958        });
1959        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1960
1961        //   c. Add at the end of the item list (including off the length)
1962        set_labeled_items(&pane, ["A", "B*", "C"], cx);
1963        pane.update(cx, |pane, cx| {
1964            pane.add_item(
1965                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1966                false,
1967                false,
1968                Some(5),
1969                cx,
1970            );
1971        });
1972        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1973
1974        // 2. Add without a destination index
1975        //   a. Add with active item at the start of the item list
1976        set_labeled_items(&pane, ["A*", "B", "C"], cx);
1977        pane.update(cx, |pane, cx| {
1978            pane.add_item(
1979                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1980                false,
1981                false,
1982                None,
1983                cx,
1984            );
1985        });
1986        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
1987
1988        //   b. Add with active item at the end of the item list
1989        set_labeled_items(&pane, ["A", "B", "C*"], cx);
1990        pane.update(cx, |pane, cx| {
1991            pane.add_item(
1992                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1993                false,
1994                false,
1995                None,
1996                cx,
1997            );
1998        });
1999        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2000    }
2001
2002    #[gpui::test]
2003    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2004        cx.foreground().forbid_parking();
2005        init_test(cx);
2006        let fs = FakeFs::new(cx.background());
2007
2008        let project = Project::test(fs, None, cx).await;
2009        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2010        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2011
2012        // 1. Add with a destination index
2013        //   1a. Add before the active item
2014        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2015        pane.update(cx, |pane, cx| {
2016            pane.add_item(d, false, false, Some(0), cx);
2017        });
2018        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2019
2020        //   1b. Add after the active item
2021        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2022        pane.update(cx, |pane, cx| {
2023            pane.add_item(d, false, false, Some(2), cx);
2024        });
2025        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2026
2027        //   1c. Add at the end of the item list (including off the length)
2028        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2029        pane.update(cx, |pane, cx| {
2030            pane.add_item(a, false, false, Some(5), cx);
2031        });
2032        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2033
2034        //   1d. Add same item to active index
2035        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2036        pane.update(cx, |pane, cx| {
2037            pane.add_item(b, false, false, Some(1), cx);
2038        });
2039        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2040
2041        //   1e. Add item to index after same item in last position
2042        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2043        pane.update(cx, |pane, cx| {
2044            pane.add_item(c, false, false, Some(2), cx);
2045        });
2046        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2047
2048        // 2. Add without a destination index
2049        //   2a. Add with active item at the start of the item list
2050        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2051        pane.update(cx, |pane, cx| {
2052            pane.add_item(d, false, false, None, cx);
2053        });
2054        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2055
2056        //   2b. Add with active item at the end of the item list
2057        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2058        pane.update(cx, |pane, cx| {
2059            pane.add_item(a, false, false, None, cx);
2060        });
2061        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2062
2063        //   2c. Add active item to active item at end of list
2064        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2065        pane.update(cx, |pane, cx| {
2066            pane.add_item(c, false, false, None, cx);
2067        });
2068        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2069
2070        //   2d. Add active item to active item at start of list
2071        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2072        pane.update(cx, |pane, cx| {
2073            pane.add_item(a, false, false, None, cx);
2074        });
2075        assert_item_labels(&pane, ["A*", "B", "C"], cx);
2076    }
2077
2078    #[gpui::test]
2079    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2080        cx.foreground().forbid_parking();
2081        init_test(cx);
2082        let fs = FakeFs::new(cx.background());
2083
2084        let project = Project::test(fs, None, cx).await;
2085        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2086        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2087
2088        // singleton view
2089        pane.update(cx, |pane, cx| {
2090            let item = TestItem::new()
2091                .with_singleton(true)
2092                .with_label("buffer 1")
2093                .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2094
2095            pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2096        });
2097        assert_item_labels(&pane, ["buffer 1*"], cx);
2098
2099        // new singleton view with the same project entry
2100        pane.update(cx, |pane, cx| {
2101            let item = TestItem::new()
2102                .with_singleton(true)
2103                .with_label("buffer 1")
2104                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2105
2106            pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2107        });
2108        assert_item_labels(&pane, ["buffer 1*"], cx);
2109
2110        // new singleton view with different project entry
2111        pane.update(cx, |pane, cx| {
2112            let item = TestItem::new()
2113                .with_singleton(true)
2114                .with_label("buffer 2")
2115                .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2116            pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2117        });
2118        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2119
2120        // new multibuffer view with the same project entry
2121        pane.update(cx, |pane, cx| {
2122            let item = TestItem::new()
2123                .with_singleton(false)
2124                .with_label("multibuffer 1")
2125                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2126
2127            pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2128        });
2129        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2130
2131        // another multibuffer view with the same project entry
2132        pane.update(cx, |pane, cx| {
2133            let item = TestItem::new()
2134                .with_singleton(false)
2135                .with_label("multibuffer 1b")
2136                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2137
2138            pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2139        });
2140        assert_item_labels(
2141            &pane,
2142            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2143            cx,
2144        );
2145    }
2146
2147    #[gpui::test]
2148    async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2149        init_test(cx);
2150        let fs = FakeFs::new(cx.background());
2151
2152        let project = Project::test(fs, None, cx).await;
2153        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2154        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2155
2156        add_labeled_item(&pane, "A", false, cx);
2157        add_labeled_item(&pane, "B", false, cx);
2158        add_labeled_item(&pane, "C", false, cx);
2159        add_labeled_item(&pane, "D", false, cx);
2160        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2161
2162        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2163        add_labeled_item(&pane, "1", false, cx);
2164        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2165
2166        pane.update(cx, |pane, cx| pane.close_active_item(&CloseActiveItem, cx))
2167            .unwrap()
2168            .await
2169            .unwrap();
2170        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2171
2172        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2173        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2174
2175        pane.update(cx, |pane, cx| pane.close_active_item(&CloseActiveItem, cx))
2176            .unwrap()
2177            .await
2178            .unwrap();
2179        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2180
2181        pane.update(cx, |pane, cx| pane.close_active_item(&CloseActiveItem, cx))
2182            .unwrap()
2183            .await
2184            .unwrap();
2185        assert_item_labels(&pane, ["A", "C*"], cx);
2186
2187        pane.update(cx, |pane, cx| pane.close_active_item(&CloseActiveItem, cx))
2188            .unwrap()
2189            .await
2190            .unwrap();
2191        assert_item_labels(&pane, ["A*"], cx);
2192    }
2193
2194    #[gpui::test]
2195    async fn test_close_inactive_items(cx: &mut TestAppContext) {
2196        init_test(cx);
2197        let fs = FakeFs::new(cx.background());
2198
2199        let project = Project::test(fs, None, cx).await;
2200        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2201        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2202
2203        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2204
2205        pane.update(cx, |pane, cx| {
2206            pane.close_inactive_items(&CloseInactiveItems, cx)
2207        })
2208        .unwrap()
2209        .await
2210        .unwrap();
2211        assert_item_labels(&pane, ["C*"], cx);
2212    }
2213
2214    #[gpui::test]
2215    async fn test_close_clean_items(cx: &mut TestAppContext) {
2216        init_test(cx);
2217        let fs = FakeFs::new(cx.background());
2218
2219        let project = Project::test(fs, None, cx).await;
2220        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2221        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2222
2223        add_labeled_item(&pane, "A", true, cx);
2224        add_labeled_item(&pane, "B", false, cx);
2225        add_labeled_item(&pane, "C", true, cx);
2226        add_labeled_item(&pane, "D", false, cx);
2227        add_labeled_item(&pane, "E", false, cx);
2228        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2229
2230        pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2231            .unwrap()
2232            .await
2233            .unwrap();
2234        assert_item_labels(&pane, ["A^", "C*^"], cx);
2235    }
2236
2237    #[gpui::test]
2238    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2239        init_test(cx);
2240        let fs = FakeFs::new(cx.background());
2241
2242        let project = Project::test(fs, None, cx).await;
2243        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2244        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2245
2246        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2247
2248        pane.update(cx, |pane, cx| {
2249            pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2250        })
2251        .unwrap()
2252        .await
2253        .unwrap();
2254        assert_item_labels(&pane, ["C*", "D", "E"], cx);
2255    }
2256
2257    #[gpui::test]
2258    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2259        init_test(cx);
2260        let fs = FakeFs::new(cx.background());
2261
2262        let project = Project::test(fs, None, cx).await;
2263        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2264        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2265
2266        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2267
2268        pane.update(cx, |pane, cx| {
2269            pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2270        })
2271        .unwrap()
2272        .await
2273        .unwrap();
2274        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2275    }
2276
2277    #[gpui::test]
2278    async fn test_close_all_items(cx: &mut TestAppContext) {
2279        init_test(cx);
2280        let fs = FakeFs::new(cx.background());
2281
2282        let project = Project::test(fs, None, cx).await;
2283        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2284        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2285
2286        add_labeled_item(&pane, "A", false, cx);
2287        add_labeled_item(&pane, "B", false, cx);
2288        add_labeled_item(&pane, "C", false, cx);
2289        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2290
2291        pane.update(cx, |pane, cx| pane.close_all_items(&CloseAllItems, cx))
2292            .unwrap()
2293            .await
2294            .unwrap();
2295        assert_item_labels(&pane, [], cx);
2296    }
2297
2298    fn init_test(cx: &mut TestAppContext) {
2299        cx.update(|cx| {
2300            cx.set_global(SettingsStore::test(cx));
2301            theme::init((), cx);
2302            crate::init_settings(cx);
2303        });
2304    }
2305
2306    fn add_labeled_item(
2307        pane: &ViewHandle<Pane>,
2308        label: &str,
2309        is_dirty: bool,
2310        cx: &mut TestAppContext,
2311    ) -> Box<ViewHandle<TestItem>> {
2312        pane.update(cx, |pane, cx| {
2313            let labeled_item =
2314                Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2315            pane.add_item(labeled_item.clone(), false, false, None, cx);
2316            labeled_item
2317        })
2318    }
2319
2320    fn set_labeled_items<const COUNT: usize>(
2321        pane: &ViewHandle<Pane>,
2322        labels: [&str; COUNT],
2323        cx: &mut TestAppContext,
2324    ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2325        pane.update(cx, |pane, cx| {
2326            pane.items.clear();
2327            let mut active_item_index = 0;
2328
2329            let mut index = 0;
2330            let items = labels.map(|mut label| {
2331                if label.ends_with("*") {
2332                    label = label.trim_end_matches("*");
2333                    active_item_index = index;
2334                }
2335
2336                let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2337                pane.add_item(labeled_item.clone(), false, false, None, cx);
2338                index += 1;
2339                labeled_item
2340            });
2341
2342            pane.activate_item(active_item_index, false, false, cx);
2343
2344            items
2345        })
2346    }
2347
2348    // Assert the item label, with the active item label suffixed with a '*'
2349    fn assert_item_labels<const COUNT: usize>(
2350        pane: &ViewHandle<Pane>,
2351        expected_states: [&str; COUNT],
2352        cx: &mut TestAppContext,
2353    ) {
2354        pane.read_with(cx, |pane, cx| {
2355            let actual_states = pane
2356                .items
2357                .iter()
2358                .enumerate()
2359                .map(|(ix, item)| {
2360                    let mut state = item
2361                        .as_any()
2362                        .downcast_ref::<TestItem>()
2363                        .unwrap()
2364                        .read(cx)
2365                        .label
2366                        .clone();
2367                    if ix == pane.active_item_index {
2368                        state.push('*');
2369                    }
2370                    if item.is_dirty(cx) {
2371                        state.push('^');
2372                    }
2373                    state
2374                })
2375                .collect::<Vec<_>>();
2376
2377            assert_eq!(
2378                actual_states, expected_states,
2379                "pane items do not match expectation"
2380            );
2381        })
2382    }
2383}