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 TabDragReceiver {}
1154                let mut receiver =
1155                    dragged_item_receiver::<TabDragReceiver, _>(ix, ix, true, None, cx, {
1156                        let item = item.clone();
1157                        let pane = pane.clone();
1158                        let detail = detail.clone();
1159
1160                        let theme = cx.global::<Settings>().theme.clone();
1161
1162                        move |mouse_state, cx| {
1163                            let tab_style =
1164                                theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1165                            let hovered = mouse_state.hovered();
1166
1167                            enum Tab {}
1168                            MouseEventHandler::<Tab>::new(ix, cx, |_, cx| {
1169                                Self::render_tab(
1170                                    &item,
1171                                    pane.clone(),
1172                                    ix == 0,
1173                                    detail,
1174                                    hovered,
1175                                    tab_style,
1176                                    cx,
1177                                )
1178                            })
1179                            .on_down(MouseButton::Left, move |_, cx| {
1180                                cx.dispatch_action(ActivateItem(ix));
1181                            })
1182                            .on_click(MouseButton::Middle, {
1183                                let item = item.clone();
1184                                move |_, cx: &mut EventContext| {
1185                                    cx.dispatch_action(CloseItem {
1186                                        item_id: item.id(),
1187                                        pane: pane.clone(),
1188                                    })
1189                                }
1190                            })
1191                            .boxed()
1192                        }
1193                    });
1194
1195                if !pane_active || !tab_active {
1196                    receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1197                }
1198
1199                receiver
1200                    .as_draggable(
1201                        DraggedItem {
1202                            item,
1203                            pane: pane.clone(),
1204                        },
1205                        {
1206                            let theme = cx.global::<Settings>().theme.clone();
1207
1208                            let detail = detail.clone();
1209                            move |dragged_item, cx: &mut RenderContext<Workspace>| {
1210                                let tab_style = &theme.workspace.tab_bar.dragged_tab;
1211                                Self::render_tab(
1212                                    &dragged_item.item,
1213                                    dragged_item.pane.clone(),
1214                                    false,
1215                                    detail,
1216                                    false,
1217                                    &tab_style,
1218                                    cx,
1219                                )
1220                            }
1221                        },
1222                    )
1223                    .boxed()
1224            })
1225        }
1226
1227        // Use the inactive tab style along with the current pane's active status to decide how to render
1228        // the filler
1229        let filler_index = self.items.len();
1230        let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1231        enum Filler {}
1232        row.add_child(
1233            dragged_item_receiver::<Filler, _>(0, filler_index, true, None, cx, |_, _| {
1234                Empty::new()
1235                    .contained()
1236                    .with_style(filler_style.container)
1237                    .with_border(filler_style.container.border)
1238                    .boxed()
1239            })
1240            .flex(1., true)
1241            .named("filler"),
1242        );
1243
1244        row
1245    }
1246
1247    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1248        let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1249
1250        let mut tab_descriptions = HashMap::default();
1251        let mut done = false;
1252        while !done {
1253            done = true;
1254
1255            // Store item indices by their tab description.
1256            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1257                if let Some(description) = item.tab_description(*detail, cx) {
1258                    if *detail == 0
1259                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1260                    {
1261                        tab_descriptions
1262                            .entry(description)
1263                            .or_insert(Vec::new())
1264                            .push(ix);
1265                    }
1266                }
1267            }
1268
1269            // If two or more items have the same tab description, increase their level
1270            // of detail and try again.
1271            for (_, item_ixs) in tab_descriptions.drain() {
1272                if item_ixs.len() > 1 {
1273                    done = false;
1274                    for ix in item_ixs {
1275                        tab_details[ix] += 1;
1276                    }
1277                }
1278            }
1279        }
1280
1281        tab_details
1282    }
1283
1284    fn render_tab<V: View>(
1285        item: &Box<dyn ItemHandle>,
1286        pane: WeakViewHandle<Pane>,
1287        first: bool,
1288        detail: Option<usize>,
1289        hovered: bool,
1290        tab_style: &theme::Tab,
1291        cx: &mut RenderContext<V>,
1292    ) -> ElementBox {
1293        let title = item.tab_content(detail, &tab_style, cx);
1294        let mut container = tab_style.container.clone();
1295        if first {
1296            container.border.left = false;
1297        }
1298
1299        Flex::row()
1300            .with_child(
1301                Align::new({
1302                    let diameter = 7.0;
1303                    let icon_color = if item.has_conflict(cx) {
1304                        Some(tab_style.icon_conflict)
1305                    } else if item.is_dirty(cx) {
1306                        Some(tab_style.icon_dirty)
1307                    } else {
1308                        None
1309                    };
1310
1311                    ConstrainedBox::new(
1312                        Canvas::new(move |bounds, _, cx| {
1313                            if let Some(color) = icon_color {
1314                                let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1315                                cx.scene.push_quad(Quad {
1316                                    bounds: square,
1317                                    background: Some(color),
1318                                    border: Default::default(),
1319                                    corner_radius: diameter / 2.,
1320                                });
1321                            }
1322                        })
1323                        .boxed(),
1324                    )
1325                    .with_width(diameter)
1326                    .with_height(diameter)
1327                    .boxed()
1328                })
1329                .boxed(),
1330            )
1331            .with_child(
1332                Container::new(Align::new(title).boxed())
1333                    .with_style(ContainerStyle {
1334                        margin: Margin {
1335                            left: tab_style.spacing,
1336                            right: tab_style.spacing,
1337                            ..Default::default()
1338                        },
1339                        ..Default::default()
1340                    })
1341                    .boxed(),
1342            )
1343            .with_child(
1344                Align::new(
1345                    ConstrainedBox::new(if hovered {
1346                        let item_id = item.id();
1347                        enum TabCloseButton {}
1348                        let icon = Svg::new("icons/x_mark_8.svg");
1349                        MouseEventHandler::<TabCloseButton>::new(item_id, cx, |mouse_state, _| {
1350                            if mouse_state.hovered() {
1351                                icon.with_color(tab_style.icon_close_active).boxed()
1352                            } else {
1353                                icon.with_color(tab_style.icon_close).boxed()
1354                            }
1355                        })
1356                        .with_padding(Padding::uniform(4.))
1357                        .with_cursor_style(CursorStyle::PointingHand)
1358                        .on_click(MouseButton::Left, {
1359                            let pane = pane.clone();
1360                            move |_, cx| {
1361                                cx.dispatch_action(CloseItem {
1362                                    item_id,
1363                                    pane: pane.clone(),
1364                                })
1365                            }
1366                        })
1367                        .named("close-tab-icon")
1368                    } else {
1369                        Empty::new().boxed()
1370                    })
1371                    .with_width(tab_style.icon_width)
1372                    .boxed(),
1373                )
1374                .boxed(),
1375            )
1376            .contained()
1377            .with_style(container)
1378            .constrained()
1379            .with_height(tab_style.height)
1380            .boxed()
1381    }
1382
1383    fn render_tab_bar_buttons(
1384        &mut self,
1385        theme: &Theme,
1386        cx: &mut RenderContext<Self>,
1387    ) -> ElementBox {
1388        Flex::row()
1389            // New menu
1390            .with_child(tab_bar_button(0, "icons/plus_12.svg", cx, |position| {
1391                DeployNewMenu { position }
1392            }))
1393            .with_child(
1394                self.docked
1395                    .map(|anchor| {
1396                        // Add the dock menu button if this pane is a dock
1397                        let dock_icon = icon_for_dock_anchor(anchor);
1398
1399                        tab_bar_button(1, dock_icon, cx, |position| DeployDockMenu { position })
1400                    })
1401                    .unwrap_or_else(|| {
1402                        // Add the split menu if this pane is not a dock
1403                        tab_bar_button(2, "icons/split_12.svg", cx, |position| DeploySplitMenu {
1404                            position,
1405                        })
1406                    }),
1407            )
1408            // Add the close dock button if this pane is a dock
1409            .with_children(
1410                self.docked
1411                    .map(|_| tab_bar_button(3, "icons/x_mark_8.svg", cx, |_| HideDock)),
1412            )
1413            .contained()
1414            .with_style(theme.workspace.tab_bar.pane_button_container)
1415            .flex(1., false)
1416            .boxed()
1417    }
1418}
1419
1420impl Entity for Pane {
1421    type Event = Event;
1422}
1423
1424impl View for Pane {
1425    fn ui_name() -> &'static str {
1426        "Pane"
1427    }
1428
1429    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1430        let this = cx.handle();
1431
1432        enum MouseNavigationHandler {}
1433
1434        Stack::new()
1435            .with_child(
1436                MouseEventHandler::<MouseNavigationHandler>::new(0, cx, |_, cx| {
1437                    let active_item_index = self.active_item_index;
1438
1439                    if let Some(active_item) = self.active_item() {
1440                        Flex::column()
1441                            .with_child({
1442                                let theme = cx.global::<Settings>().theme.clone();
1443
1444                                let mut stack = Stack::new();
1445
1446                                enum TabBarEventHandler {}
1447                                stack.add_child(
1448                                    MouseEventHandler::<TabBarEventHandler>::new(0, cx, |_, _| {
1449                                        Empty::new()
1450                                            .contained()
1451                                            .with_style(theme.workspace.tab_bar.container)
1452                                            .boxed()
1453                                    })
1454                                    .on_down(MouseButton::Left, move |_, cx| {
1455                                        cx.dispatch_action(ActivateItem(active_item_index));
1456                                    })
1457                                    .boxed(),
1458                                );
1459
1460                                let mut tab_row = Flex::row()
1461                                    .with_child(self.render_tabs(cx).flex(1., true).named("tabs"));
1462
1463                                if self.is_active {
1464                                    tab_row.add_child(self.render_tab_bar_buttons(&theme, cx))
1465                                }
1466
1467                                stack.add_child(tab_row.boxed());
1468                                stack
1469                                    .constrained()
1470                                    .with_height(theme.workspace.tab_bar.height)
1471                                    .flex(1., false)
1472                                    .named("tab bar")
1473                            })
1474                            .with_child({
1475                                enum PaneContentTabDropTarget {}
1476                                dragged_item_receiver::<PaneContentTabDropTarget, _>(
1477                                    0,
1478                                    self.active_item_index + 1,
1479                                    false,
1480                                    if self.docked.is_some() {
1481                                        None
1482                                    } else {
1483                                        Some(100.)
1484                                    },
1485                                    cx,
1486                                    {
1487                                        let toolbar = self.toolbar.clone();
1488                                        move |_, cx| {
1489                                            Flex::column()
1490                                                .with_child(
1491                                                    ChildView::new(&toolbar, cx).expanded().boxed(),
1492                                                )
1493                                                .with_child(
1494                                                    ChildView::new(active_item, cx)
1495                                                        .flex(1., true)
1496                                                        .boxed(),
1497                                                )
1498                                                .boxed()
1499                                        }
1500                                    },
1501                                )
1502                                .flex(1., true)
1503                                .boxed()
1504                            })
1505                            .boxed()
1506                    } else {
1507                        enum EmptyPane {}
1508                        let theme = cx.global::<Settings>().theme.clone();
1509
1510                        dragged_item_receiver::<EmptyPane, _>(0, 0, false, None, cx, |_, _| {
1511                            Empty::new()
1512                                .contained()
1513                                .with_background_color(theme.workspace.background)
1514                                .boxed()
1515                        })
1516                        .on_down(MouseButton::Left, |_, cx| {
1517                            cx.focus_parent_view();
1518                        })
1519                        .boxed()
1520                    }
1521                })
1522                .on_down(MouseButton::Navigate(NavigationDirection::Back), {
1523                    let this = this.clone();
1524                    move |_, cx| {
1525                        cx.dispatch_action(GoBack {
1526                            pane: Some(this.clone()),
1527                        });
1528                    }
1529                })
1530                .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1531                    let this = this.clone();
1532                    move |_, cx| {
1533                        cx.dispatch_action(GoForward {
1534                            pane: Some(this.clone()),
1535                        })
1536                    }
1537                })
1538                .boxed(),
1539            )
1540            .with_child(ChildView::new(&self.tab_bar_context_menu, cx).boxed())
1541            .named("pane")
1542    }
1543
1544    fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1545        if let Some(active_item) = self.active_item() {
1546            if cx.is_self_focused() {
1547                // Pane was focused directly. We need to either focus a view inside the active item,
1548                // or focus the active item itself
1549                if let Some(weak_last_focused_view) =
1550                    self.last_focused_view_by_item.get(&active_item.id())
1551                {
1552                    if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1553                        cx.focus(last_focused_view);
1554                        return;
1555                    } else {
1556                        self.last_focused_view_by_item.remove(&active_item.id());
1557                    }
1558                }
1559
1560                cx.focus(active_item);
1561            } else if focused != self.tab_bar_context_menu {
1562                self.last_focused_view_by_item
1563                    .insert(active_item.id(), focused.downgrade());
1564            }
1565        }
1566    }
1567
1568    fn keymap_context(&self, _: &AppContext) -> KeymapContext {
1569        let mut keymap = Self::default_keymap_context();
1570        if self.docked.is_some() {
1571            keymap.add_identifier("docked");
1572        }
1573        keymap
1574    }
1575}
1576
1577fn tab_bar_button<A: Action>(
1578    index: usize,
1579    icon: &'static str,
1580    cx: &mut RenderContext<Pane>,
1581    action_builder: impl 'static + Fn(Vector2F) -> A,
1582) -> ElementBox {
1583    enum TabBarButton {}
1584
1585    MouseEventHandler::<TabBarButton>::new(index, cx, |mouse_state, cx| {
1586        let theme = &cx.global::<Settings>().theme.workspace.tab_bar;
1587        let style = theme.pane_button.style_for(mouse_state, false);
1588        Svg::new(icon)
1589            .with_color(style.color)
1590            .constrained()
1591            .with_width(style.icon_width)
1592            .aligned()
1593            .constrained()
1594            .with_width(style.button_width)
1595            .with_height(style.button_width)
1596            // .aligned()
1597            .boxed()
1598    })
1599    .with_cursor_style(CursorStyle::PointingHand)
1600    .on_click(MouseButton::Left, move |e, cx| {
1601        cx.dispatch_action(action_builder(e.region.lower_right()));
1602    })
1603    .flex(1., false)
1604    .boxed()
1605}
1606
1607impl ItemNavHistory {
1608    pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut MutableAppContext) {
1609        self.history.borrow_mut().push(data, self.item.clone(), cx);
1610    }
1611
1612    pub fn pop_backward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1613        self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1614    }
1615
1616    pub fn pop_forward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1617        self.history
1618            .borrow_mut()
1619            .pop(NavigationMode::GoingForward, cx)
1620    }
1621}
1622
1623impl NavHistory {
1624    fn set_mode(&mut self, mode: NavigationMode) {
1625        self.mode = mode;
1626    }
1627
1628    fn disable(&mut self) {
1629        self.mode = NavigationMode::Disabled;
1630    }
1631
1632    fn enable(&mut self) {
1633        self.mode = NavigationMode::Normal;
1634    }
1635
1636    fn pop(&mut self, mode: NavigationMode, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1637        let entry = match mode {
1638            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1639                return None
1640            }
1641            NavigationMode::GoingBack => &mut self.backward_stack,
1642            NavigationMode::GoingForward => &mut self.forward_stack,
1643            NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1644        }
1645        .pop_back();
1646        if entry.is_some() {
1647            self.did_update(cx);
1648        }
1649        entry
1650    }
1651
1652    fn push<D: 'static + Any>(
1653        &mut self,
1654        data: Option<D>,
1655        item: Rc<dyn WeakItemHandle>,
1656        cx: &mut MutableAppContext,
1657    ) {
1658        match self.mode {
1659            NavigationMode::Disabled => {}
1660            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1661                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1662                    self.backward_stack.pop_front();
1663                }
1664                self.backward_stack.push_back(NavigationEntry {
1665                    item,
1666                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1667                });
1668                self.forward_stack.clear();
1669            }
1670            NavigationMode::GoingBack => {
1671                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1672                    self.forward_stack.pop_front();
1673                }
1674                self.forward_stack.push_back(NavigationEntry {
1675                    item,
1676                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1677                });
1678            }
1679            NavigationMode::GoingForward => {
1680                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1681                    self.backward_stack.pop_front();
1682                }
1683                self.backward_stack.push_back(NavigationEntry {
1684                    item,
1685                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1686                });
1687            }
1688            NavigationMode::ClosingItem => {
1689                if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1690                    self.closed_stack.pop_front();
1691                }
1692                self.closed_stack.push_back(NavigationEntry {
1693                    item,
1694                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1695                });
1696            }
1697        }
1698        self.did_update(cx);
1699    }
1700
1701    fn did_update(&self, cx: &mut MutableAppContext) {
1702        if let Some(pane) = self.pane.upgrade(cx) {
1703            cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1704        }
1705    }
1706}
1707
1708#[cfg(test)]
1709mod tests {
1710    use std::sync::Arc;
1711
1712    use super::*;
1713    use crate::item::test::{TestItem, TestProjectItem};
1714    use gpui::{executor::Deterministic, TestAppContext};
1715    use project::FakeFs;
1716
1717    #[gpui::test]
1718    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
1719        cx.foreground().forbid_parking();
1720        Settings::test_async(cx);
1721        let fs = FakeFs::new(cx.background());
1722
1723        let project = Project::test(fs, None, cx).await;
1724        let (_, workspace) = cx.add_window(|cx| {
1725            Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
1726        });
1727        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1728
1729        // 1. Add with a destination index
1730        //   a. Add before the active item
1731        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1732        workspace.update(cx, |workspace, cx| {
1733            Pane::add_item(
1734                workspace,
1735                &pane,
1736                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1737                false,
1738                false,
1739                Some(0),
1740                cx,
1741            );
1742        });
1743        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1744
1745        //   b. Add after the active item
1746        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1747        workspace.update(cx, |workspace, cx| {
1748            Pane::add_item(
1749                workspace,
1750                &pane,
1751                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1752                false,
1753                false,
1754                Some(2),
1755                cx,
1756            );
1757        });
1758        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1759
1760        //   c. Add at the end of the item list (including off the length)
1761        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1762        workspace.update(cx, |workspace, cx| {
1763            Pane::add_item(
1764                workspace,
1765                &pane,
1766                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1767                false,
1768                false,
1769                Some(5),
1770                cx,
1771            );
1772        });
1773        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1774
1775        // 2. Add without a destination index
1776        //   a. Add with active item at the start of the item list
1777        set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1778        workspace.update(cx, |workspace, cx| {
1779            Pane::add_item(
1780                workspace,
1781                &pane,
1782                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1783                false,
1784                false,
1785                None,
1786                cx,
1787            );
1788        });
1789        set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
1790
1791        //   b. Add with active item at the end of the item list
1792        set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1793        workspace.update(cx, |workspace, cx| {
1794            Pane::add_item(
1795                workspace,
1796                &pane,
1797                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1798                false,
1799                false,
1800                None,
1801                cx,
1802            );
1803        });
1804        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1805    }
1806
1807    #[gpui::test]
1808    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
1809        cx.foreground().forbid_parking();
1810        Settings::test_async(cx);
1811        let fs = FakeFs::new(cx.background());
1812
1813        let project = Project::test(fs, None, cx).await;
1814        let (_, workspace) = cx.add_window(|cx| {
1815            Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
1816        });
1817        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1818
1819        // 1. Add with a destination index
1820        //   1a. Add before the active item
1821        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1822        workspace.update(cx, |workspace, cx| {
1823            Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
1824        });
1825        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1826
1827        //   1b. Add after the active item
1828        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1829        workspace.update(cx, |workspace, cx| {
1830            Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
1831        });
1832        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1833
1834        //   1c. Add at the end of the item list (including off the length)
1835        let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1836        workspace.update(cx, |workspace, cx| {
1837            Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
1838        });
1839        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1840
1841        //   1d. Add same item to active index
1842        let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1843        workspace.update(cx, |workspace, cx| {
1844            Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
1845        });
1846        assert_item_labels(&pane, ["A", "B*", "C"], cx);
1847
1848        //   1e. Add item to index after same item in last position
1849        let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1850        workspace.update(cx, |workspace, cx| {
1851            Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
1852        });
1853        assert_item_labels(&pane, ["A", "B", "C*"], cx);
1854
1855        // 2. Add without a destination index
1856        //   2a. Add with active item at the start of the item list
1857        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
1858        workspace.update(cx, |workspace, cx| {
1859            Pane::add_item(workspace, &pane, d, false, false, None, cx);
1860        });
1861        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
1862
1863        //   2b. Add with active item at the end of the item list
1864        let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
1865        workspace.update(cx, |workspace, cx| {
1866            Pane::add_item(workspace, &pane, a, false, false, None, cx);
1867        });
1868        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1869
1870        //   2c. Add active item to active item at end of list
1871        let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1872        workspace.update(cx, |workspace, cx| {
1873            Pane::add_item(workspace, &pane, c, false, false, None, cx);
1874        });
1875        assert_item_labels(&pane, ["A", "B", "C*"], cx);
1876
1877        //   2d. Add active item to active item at start of list
1878        let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1879        workspace.update(cx, |workspace, cx| {
1880            Pane::add_item(workspace, &pane, a, false, false, None, cx);
1881        });
1882        assert_item_labels(&pane, ["A*", "B", "C"], cx);
1883    }
1884
1885    #[gpui::test]
1886    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
1887        cx.foreground().forbid_parking();
1888        Settings::test_async(cx);
1889        let fs = FakeFs::new(cx.background());
1890
1891        let project = Project::test(fs, None, cx).await;
1892        let (_, workspace) = cx.add_window(|cx| {
1893            Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
1894        });
1895        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1896
1897        // singleton view
1898        workspace.update(cx, |workspace, cx| {
1899            let item = TestItem::new()
1900                .with_singleton(true)
1901                .with_label("buffer 1")
1902                .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
1903
1904            Pane::add_item(
1905                workspace,
1906                &pane,
1907                Box::new(cx.add_view(|_| item)),
1908                false,
1909                false,
1910                None,
1911                cx,
1912            );
1913        });
1914        assert_item_labels(&pane, ["buffer 1*"], cx);
1915
1916        // new singleton view with the same project entry
1917        workspace.update(cx, |workspace, cx| {
1918            let item = TestItem::new()
1919                .with_singleton(true)
1920                .with_label("buffer 1")
1921                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
1922
1923            Pane::add_item(
1924                workspace,
1925                &pane,
1926                Box::new(cx.add_view(|_| item)),
1927                false,
1928                false,
1929                None,
1930                cx,
1931            );
1932        });
1933        assert_item_labels(&pane, ["buffer 1*"], cx);
1934
1935        // new singleton view with different project entry
1936        workspace.update(cx, |workspace, cx| {
1937            let item = TestItem::new()
1938                .with_singleton(true)
1939                .with_label("buffer 2")
1940                .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
1941
1942            Pane::add_item(
1943                workspace,
1944                &pane,
1945                Box::new(cx.add_view(|_| item)),
1946                false,
1947                false,
1948                None,
1949                cx,
1950            );
1951        });
1952        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
1953
1954        // new multibuffer view with the same project entry
1955        workspace.update(cx, |workspace, cx| {
1956            let item = TestItem::new()
1957                .with_singleton(false)
1958                .with_label("multibuffer 1")
1959                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
1960
1961            Pane::add_item(
1962                workspace,
1963                &pane,
1964                Box::new(cx.add_view(|_| item)),
1965                false,
1966                false,
1967                None,
1968                cx,
1969            );
1970        });
1971        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
1972
1973        // another multibuffer view with the same project entry
1974        workspace.update(cx, |workspace, cx| {
1975            let item = TestItem::new()
1976                .with_singleton(false)
1977                .with_label("multibuffer 1b")
1978                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
1979
1980            Pane::add_item(
1981                workspace,
1982                &pane,
1983                Box::new(cx.add_view(|_| item)),
1984                false,
1985                false,
1986                None,
1987                cx,
1988            );
1989        });
1990        assert_item_labels(
1991            &pane,
1992            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
1993            cx,
1994        );
1995    }
1996
1997    #[gpui::test]
1998    async fn test_remove_item_ordering(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1999        Settings::test_async(cx);
2000        let fs = FakeFs::new(cx.background());
2001
2002        let project = Project::test(fs, None, cx).await;
2003        let (_, workspace) =
2004            cx.add_window(|cx| Workspace::new(None, 0, project, |_, _| unimplemented!(), cx));
2005        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2006
2007        add_labled_item(&workspace, &pane, "A", cx);
2008        add_labled_item(&workspace, &pane, "B", cx);
2009        add_labled_item(&workspace, &pane, "C", cx);
2010        add_labled_item(&workspace, &pane, "D", cx);
2011        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2012
2013        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2014        add_labled_item(&workspace, &pane, "1", cx);
2015        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2016
2017        workspace.update(cx, |workspace, cx| {
2018            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2019        });
2020        deterministic.run_until_parked();
2021        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2022
2023        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2024        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2025
2026        workspace.update(cx, |workspace, cx| {
2027            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2028        });
2029        deterministic.run_until_parked();
2030        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2031
2032        workspace.update(cx, |workspace, cx| {
2033            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2034        });
2035        deterministic.run_until_parked();
2036        assert_item_labels(&pane, ["A", "C*"], cx);
2037
2038        workspace.update(cx, |workspace, cx| {
2039            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2040        });
2041        deterministic.run_until_parked();
2042        assert_item_labels(&pane, ["A*"], cx);
2043    }
2044
2045    fn add_labled_item(
2046        workspace: &ViewHandle<Workspace>,
2047        pane: &ViewHandle<Pane>,
2048        label: &str,
2049        cx: &mut TestAppContext,
2050    ) -> Box<ViewHandle<TestItem>> {
2051        workspace.update(cx, |workspace, cx| {
2052            let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2053
2054            Pane::add_item(
2055                workspace,
2056                pane,
2057                labeled_item.clone(),
2058                false,
2059                false,
2060                None,
2061                cx,
2062            );
2063
2064            labeled_item
2065        })
2066    }
2067
2068    fn set_labeled_items<const COUNT: usize>(
2069        workspace: &ViewHandle<Workspace>,
2070        pane: &ViewHandle<Pane>,
2071        labels: [&str; COUNT],
2072        cx: &mut TestAppContext,
2073    ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2074        pane.update(cx, |pane, _| {
2075            pane.items.clear();
2076        });
2077
2078        workspace.update(cx, |workspace, cx| {
2079            let mut active_item_index = 0;
2080
2081            let mut index = 0;
2082            let items = labels.map(|mut label| {
2083                if label.ends_with("*") {
2084                    label = label.trim_end_matches("*");
2085                    active_item_index = index;
2086                }
2087
2088                let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2089                Pane::add_item(
2090                    workspace,
2091                    pane,
2092                    labeled_item.clone(),
2093                    false,
2094                    false,
2095                    None,
2096                    cx,
2097                );
2098                index += 1;
2099                labeled_item
2100            });
2101
2102            pane.update(cx, |pane, cx| {
2103                pane.activate_item(active_item_index, false, false, cx)
2104            });
2105
2106            items
2107        })
2108    }
2109
2110    // Assert the item label, with the active item label suffixed with a '*'
2111    fn assert_item_labels<const COUNT: usize>(
2112        pane: &ViewHandle<Pane>,
2113        expected_states: [&str; COUNT],
2114        cx: &mut TestAppContext,
2115    ) {
2116        pane.read_with(cx, |pane, cx| {
2117            let actual_states = pane
2118                .items
2119                .iter()
2120                .enumerate()
2121                .map(|(ix, item)| {
2122                    let mut state = item
2123                        .to_any()
2124                        .downcast::<TestItem>()
2125                        .unwrap()
2126                        .read(cx)
2127                        .label
2128                        .clone();
2129                    if ix == pane.active_item_index {
2130                        state.push('*');
2131                    }
2132                    state
2133                })
2134                .collect::<Vec<_>>();
2135
2136            assert_eq!(
2137                actual_states, expected_states,
2138                "pane items do not match expectation"
2139            );
2140        })
2141    }
2142}