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