pane.rs

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