pane.rs

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