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 theme = &theme.workspace.blank_pane;
1433        Stack::new()
1434            .with_children([
1435                Empty::new()
1436                    .contained()
1437                    .with_background_color(background)
1438                    .boxed(),
1439                Flex::column()
1440                    .align_children_center()
1441                    .with_children([
1442                        Stack::new()
1443                            .with_children([
1444                                theme::ui::icon(&theme.logo_shadow).aligned().boxed(),
1445                                theme::ui::icon(&theme.logo).aligned().boxed(),
1446                            ])
1447                            .contained()
1448                            .with_style(theme.logo_container)
1449                            .boxed(),
1450                        Flex::column()
1451                            .with_children({
1452                                enum KeyboardHint {}
1453                                let keyboard_hint = &theme.keyboard_hint;
1454                                let workspace_id = self.workspace_id;
1455                                (self.background_actions)().into_iter().enumerate().map(
1456                                    move |(idx, (text, action))| {
1457                                        let hint_action = action.boxed_clone();
1458                                        MouseEventHandler::<KeyboardHint>::new(
1459                                            idx,
1460                                            cx,
1461                                            move |state, cx| {
1462                                                let style = keyboard_hint.style_for(state, false);
1463                                                theme::ui::keystroke_label_for(
1464                                                    cx.window_id(),
1465                                                    workspace_id,
1466                                                    text,
1467                                                    &style,
1468                                                    &style,
1469                                                    hint_action,
1470                                                )
1471                                                .boxed()
1472                                            },
1473                                        )
1474                                        .on_click(MouseButton::Left, move |_, cx| {
1475                                            cx.dispatch_any_action(action.boxed_clone())
1476                                        })
1477                                        .with_cursor_style(CursorStyle::PointingHand)
1478                                        .boxed()
1479                                    },
1480                                )
1481                            })
1482                            .contained()
1483                            .with_style(theme.keyboard_hints)
1484                            .constrained()
1485                            .with_max_width(theme.keyboard_hint_width)
1486                            .aligned()
1487                            .boxed(),
1488                    ])
1489                    .aligned()
1490                    .boxed(),
1491            ])
1492            .boxed()
1493    }
1494}
1495
1496impl Entity for Pane {
1497    type Event = Event;
1498}
1499
1500impl View for Pane {
1501    fn ui_name() -> &'static str {
1502        "Pane"
1503    }
1504
1505    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1506        let this = cx.handle();
1507
1508        enum MouseNavigationHandler {}
1509
1510        Stack::new()
1511            .with_child(
1512                MouseEventHandler::<MouseNavigationHandler>::new(0, cx, |_, cx| {
1513                    let active_item_index = self.active_item_index;
1514
1515                    if let Some(active_item) = self.active_item() {
1516                        Flex::column()
1517                            .with_child({
1518                                let theme = cx.global::<Settings>().theme.clone();
1519
1520                                let mut stack = Stack::new();
1521
1522                                enum TabBarEventHandler {}
1523                                stack.add_child(
1524                                    MouseEventHandler::<TabBarEventHandler>::new(0, cx, |_, _| {
1525                                        Empty::new()
1526                                            .contained()
1527                                            .with_style(theme.workspace.tab_bar.container)
1528                                            .boxed()
1529                                    })
1530                                    .on_down(MouseButton::Left, move |_, cx| {
1531                                        cx.dispatch_action(ActivateItem(active_item_index));
1532                                    })
1533                                    .boxed(),
1534                                );
1535
1536                                let mut tab_row = Flex::row()
1537                                    .with_child(self.render_tabs(cx).flex(1., true).named("tabs"));
1538
1539                                if self.is_active {
1540                                    tab_row.add_child(self.render_tab_bar_buttons(&theme, cx))
1541                                }
1542
1543                                stack.add_child(tab_row.boxed());
1544                                stack
1545                                    .constrained()
1546                                    .with_height(theme.workspace.tab_bar.height)
1547                                    .flex(1., false)
1548                                    .named("tab bar")
1549                            })
1550                            .with_child({
1551                                enum PaneContentTabDropTarget {}
1552                                dragged_item_receiver::<PaneContentTabDropTarget, _>(
1553                                    0,
1554                                    self.active_item_index + 1,
1555                                    false,
1556                                    if self.docked.is_some() {
1557                                        None
1558                                    } else {
1559                                        Some(100.)
1560                                    },
1561                                    cx,
1562                                    {
1563                                        let toolbar = self.toolbar.clone();
1564                                        let toolbar_hidden = toolbar.read(cx).hidden();
1565                                        move |_, cx| {
1566                                            Flex::column()
1567                                                .with_children((!toolbar_hidden).then(|| {
1568                                                    ChildView::new(&toolbar, cx).expanded().boxed()
1569                                                }))
1570                                                .with_child(
1571                                                    ChildView::new(active_item, cx)
1572                                                        .flex(1., true)
1573                                                        .boxed(),
1574                                                )
1575                                                .boxed()
1576                                        }
1577                                    },
1578                                )
1579                                .flex(1., true)
1580                                .boxed()
1581                            })
1582                            .boxed()
1583                    } else {
1584                        enum EmptyPane {}
1585                        let theme = cx.global::<Settings>().theme.clone();
1586
1587                        dragged_item_receiver::<EmptyPane, _>(0, 0, false, None, cx, |_, cx| {
1588                            self.render_blank_pane(&theme, cx)
1589                        })
1590                        .on_down(MouseButton::Left, |_, cx| {
1591                            cx.focus_parent_view();
1592                        })
1593                        .boxed()
1594                    }
1595                })
1596                .on_down(MouseButton::Navigate(NavigationDirection::Back), {
1597                    let this = this.clone();
1598                    move |_, cx| {
1599                        cx.dispatch_action(GoBack {
1600                            pane: Some(this.clone()),
1601                        });
1602                    }
1603                })
1604                .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1605                    let this = this.clone();
1606                    move |_, cx| {
1607                        cx.dispatch_action(GoForward {
1608                            pane: Some(this.clone()),
1609                        })
1610                    }
1611                })
1612                .boxed(),
1613            )
1614            .with_child(ChildView::new(&self.tab_bar_context_menu, cx).boxed())
1615            .named("pane")
1616    }
1617
1618    fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1619        if let Some(active_item) = self.active_item() {
1620            if cx.is_self_focused() {
1621                // Pane was focused directly. We need to either focus a view inside the active item,
1622                // or focus the active item itself
1623                if let Some(weak_last_focused_view) =
1624                    self.last_focused_view_by_item.get(&active_item.id())
1625                {
1626                    if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1627                        cx.focus(last_focused_view);
1628                        return;
1629                    } else {
1630                        self.last_focused_view_by_item.remove(&active_item.id());
1631                    }
1632                }
1633
1634                cx.focus(active_item);
1635            } else if focused != self.tab_bar_context_menu {
1636                self.last_focused_view_by_item
1637                    .insert(active_item.id(), focused.downgrade());
1638            }
1639        }
1640    }
1641
1642    fn keymap_context(&self, _: &AppContext) -> KeymapContext {
1643        let mut keymap = Self::default_keymap_context();
1644        if self.docked.is_some() {
1645            keymap.add_identifier("docked");
1646        }
1647        keymap
1648    }
1649}
1650
1651fn tab_bar_button<A: Action>(
1652    index: usize,
1653    icon: &'static str,
1654    cx: &mut RenderContext<Pane>,
1655    action_builder: impl 'static + Fn(Vector2F) -> A,
1656) -> ElementBox {
1657    enum TabBarButton {}
1658
1659    MouseEventHandler::<TabBarButton>::new(index, cx, |mouse_state, cx| {
1660        let theme = &cx.global::<Settings>().theme.workspace.tab_bar;
1661        let style = theme.pane_button.style_for(mouse_state, false);
1662        Svg::new(icon)
1663            .with_color(style.color)
1664            .constrained()
1665            .with_width(style.icon_width)
1666            .aligned()
1667            .constrained()
1668            .with_width(style.button_width)
1669            .with_height(style.button_width)
1670            // .aligned()
1671            .boxed()
1672    })
1673    .with_cursor_style(CursorStyle::PointingHand)
1674    .on_click(MouseButton::Left, move |e, cx| {
1675        cx.dispatch_action(action_builder(e.region.lower_right()));
1676    })
1677    .flex(1., false)
1678    .boxed()
1679}
1680
1681impl ItemNavHistory {
1682    pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut MutableAppContext) {
1683        self.history.borrow_mut().push(data, self.item.clone(), cx);
1684    }
1685
1686    pub fn pop_backward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1687        self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1688    }
1689
1690    pub fn pop_forward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1691        self.history
1692            .borrow_mut()
1693            .pop(NavigationMode::GoingForward, cx)
1694    }
1695}
1696
1697impl NavHistory {
1698    fn set_mode(&mut self, mode: NavigationMode) {
1699        self.mode = mode;
1700    }
1701
1702    fn disable(&mut self) {
1703        self.mode = NavigationMode::Disabled;
1704    }
1705
1706    fn enable(&mut self) {
1707        self.mode = NavigationMode::Normal;
1708    }
1709
1710    fn pop(&mut self, mode: NavigationMode, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1711        let entry = match mode {
1712            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1713                return None
1714            }
1715            NavigationMode::GoingBack => &mut self.backward_stack,
1716            NavigationMode::GoingForward => &mut self.forward_stack,
1717            NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1718        }
1719        .pop_back();
1720        if entry.is_some() {
1721            self.did_update(cx);
1722        }
1723        entry
1724    }
1725
1726    fn push<D: 'static + Any>(
1727        &mut self,
1728        data: Option<D>,
1729        item: Rc<dyn WeakItemHandle>,
1730        cx: &mut MutableAppContext,
1731    ) {
1732        match self.mode {
1733            NavigationMode::Disabled => {}
1734            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1735                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1736                    self.backward_stack.pop_front();
1737                }
1738                self.backward_stack.push_back(NavigationEntry {
1739                    item,
1740                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1741                });
1742                self.forward_stack.clear();
1743            }
1744            NavigationMode::GoingBack => {
1745                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1746                    self.forward_stack.pop_front();
1747                }
1748                self.forward_stack.push_back(NavigationEntry {
1749                    item,
1750                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1751                });
1752            }
1753            NavigationMode::GoingForward => {
1754                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1755                    self.backward_stack.pop_front();
1756                }
1757                self.backward_stack.push_back(NavigationEntry {
1758                    item,
1759                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1760                });
1761            }
1762            NavigationMode::ClosingItem => {
1763                if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1764                    self.closed_stack.pop_front();
1765                }
1766                self.closed_stack.push_back(NavigationEntry {
1767                    item,
1768                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1769                });
1770            }
1771        }
1772        self.did_update(cx);
1773    }
1774
1775    fn did_update(&self, cx: &mut MutableAppContext) {
1776        if let Some(pane) = self.pane.upgrade(cx) {
1777            cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1778        }
1779    }
1780}
1781
1782pub struct PaneBackdrop {
1783    child_view: usize,
1784    child: ElementBox,
1785}
1786impl PaneBackdrop {
1787    pub fn new(pane_item_view: usize, child: ElementBox) -> Self {
1788        PaneBackdrop {
1789            child,
1790            child_view: pane_item_view,
1791        }
1792    }
1793}
1794
1795impl Element for PaneBackdrop {
1796    type LayoutState = ();
1797
1798    type PaintState = ();
1799
1800    fn layout(
1801        &mut self,
1802        constraint: gpui::SizeConstraint,
1803        cx: &mut gpui::LayoutContext,
1804    ) -> (Vector2F, Self::LayoutState) {
1805        let size = self.child.layout(constraint, cx);
1806        (size, ())
1807    }
1808
1809    fn paint(
1810        &mut self,
1811        bounds: RectF,
1812        visible_bounds: RectF,
1813        _: &mut Self::LayoutState,
1814        cx: &mut gpui::PaintContext,
1815    ) -> Self::PaintState {
1816        let background = cx.global::<Settings>().theme.editor.background;
1817
1818        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
1819
1820        cx.scene.push_quad(gpui::Quad {
1821            bounds: RectF::new(bounds.origin(), bounds.size()),
1822            background: Some(background),
1823            ..Default::default()
1824        });
1825
1826        let child_view_id = self.child_view;
1827        cx.scene.push_mouse_region(
1828            MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
1829                gpui::MouseButton::Left,
1830                move |_, cx| {
1831                    let window_id = cx.window_id;
1832                    cx.focus(window_id, Some(child_view_id))
1833                },
1834            ),
1835        );
1836
1837        cx.paint_layer(Some(bounds), |cx| {
1838            self.child.paint(bounds.origin(), visible_bounds, cx)
1839        })
1840    }
1841
1842    fn rect_for_text_range(
1843        &self,
1844        range_utf16: std::ops::Range<usize>,
1845        _bounds: RectF,
1846        _visible_bounds: RectF,
1847        _layout: &Self::LayoutState,
1848        _paint: &Self::PaintState,
1849        cx: &gpui::MeasurementContext,
1850    ) -> Option<RectF> {
1851        self.child.rect_for_text_range(range_utf16, cx)
1852    }
1853
1854    fn debug(
1855        &self,
1856        _bounds: RectF,
1857        _layout: &Self::LayoutState,
1858        _paint: &Self::PaintState,
1859        cx: &gpui::DebugContext,
1860    ) -> serde_json::Value {
1861        gpui::json::json!({
1862            "type": "Pane Back Drop",
1863            "view": self.child_view,
1864            "child": self.child.debug(cx),
1865        })
1866    }
1867}
1868
1869#[cfg(test)]
1870mod tests {
1871    use std::sync::Arc;
1872
1873    use super::*;
1874    use crate::item::test::{TestItem, TestProjectItem};
1875    use gpui::{executor::Deterministic, TestAppContext};
1876    use project::FakeFs;
1877
1878    #[gpui::test]
1879    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
1880        cx.foreground().forbid_parking();
1881        Settings::test_async(cx);
1882        let fs = FakeFs::new(cx.background());
1883
1884        let project = Project::test(fs, None, cx).await;
1885        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1886        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1887
1888        // 1. Add with a destination index
1889        //   a. Add before the active item
1890        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1891        workspace.update(cx, |workspace, cx| {
1892            Pane::add_item(
1893                workspace,
1894                &pane,
1895                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1896                false,
1897                false,
1898                Some(0),
1899                cx,
1900            );
1901        });
1902        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1903
1904        //   b. Add after the active item
1905        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1906        workspace.update(cx, |workspace, cx| {
1907            Pane::add_item(
1908                workspace,
1909                &pane,
1910                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1911                false,
1912                false,
1913                Some(2),
1914                cx,
1915            );
1916        });
1917        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1918
1919        //   c. Add at the end of the item list (including off the length)
1920        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1921        workspace.update(cx, |workspace, cx| {
1922            Pane::add_item(
1923                workspace,
1924                &pane,
1925                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1926                false,
1927                false,
1928                Some(5),
1929                cx,
1930            );
1931        });
1932        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1933
1934        // 2. Add without a destination index
1935        //   a. Add with active item at the start of the item list
1936        set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1937        workspace.update(cx, |workspace, cx| {
1938            Pane::add_item(
1939                workspace,
1940                &pane,
1941                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1942                false,
1943                false,
1944                None,
1945                cx,
1946            );
1947        });
1948        set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
1949
1950        //   b. Add with active item at the end of the item list
1951        set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1952        workspace.update(cx, |workspace, cx| {
1953            Pane::add_item(
1954                workspace,
1955                &pane,
1956                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1957                false,
1958                false,
1959                None,
1960                cx,
1961            );
1962        });
1963        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1964    }
1965
1966    #[gpui::test]
1967    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
1968        cx.foreground().forbid_parking();
1969        Settings::test_async(cx);
1970        let fs = FakeFs::new(cx.background());
1971
1972        let project = Project::test(fs, None, cx).await;
1973        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1974        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1975
1976        // 1. Add with a destination index
1977        //   1a. Add before the active item
1978        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1979        workspace.update(cx, |workspace, cx| {
1980            Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
1981        });
1982        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1983
1984        //   1b. Add after the active item
1985        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1986        workspace.update(cx, |workspace, cx| {
1987            Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
1988        });
1989        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1990
1991        //   1c. Add at the end of the item list (including off the length)
1992        let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1993        workspace.update(cx, |workspace, cx| {
1994            Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
1995        });
1996        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1997
1998        //   1d. Add same item to active index
1999        let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2000        workspace.update(cx, |workspace, cx| {
2001            Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
2002        });
2003        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2004
2005        //   1e. Add item to index after same item in last position
2006        let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2007        workspace.update(cx, |workspace, cx| {
2008            Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
2009        });
2010        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2011
2012        // 2. Add without a destination index
2013        //   2a. Add with active item at the start of the item list
2014        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
2015        workspace.update(cx, |workspace, cx| {
2016            Pane::add_item(workspace, &pane, d, false, false, None, cx);
2017        });
2018        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2019
2020        //   2b. Add with active item at the end of the item list
2021        let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
2022        workspace.update(cx, |workspace, cx| {
2023            Pane::add_item(workspace, &pane, a, false, false, None, cx);
2024        });
2025        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2026
2027        //   2c. Add active item to active item at end of list
2028        let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2029        workspace.update(cx, |workspace, cx| {
2030            Pane::add_item(workspace, &pane, c, false, false, None, cx);
2031        });
2032        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2033
2034        //   2d. Add active item to active item at start of list
2035        let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2036        workspace.update(cx, |workspace, cx| {
2037            Pane::add_item(workspace, &pane, a, false, false, None, cx);
2038        });
2039        assert_item_labels(&pane, ["A*", "B", "C"], cx);
2040    }
2041
2042    #[gpui::test]
2043    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2044        cx.foreground().forbid_parking();
2045        Settings::test_async(cx);
2046        let fs = FakeFs::new(cx.background());
2047
2048        let project = Project::test(fs, None, cx).await;
2049        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2050        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2051
2052        // singleton view
2053        workspace.update(cx, |workspace, cx| {
2054            let item = TestItem::new()
2055                .with_singleton(true)
2056                .with_label("buffer 1")
2057                .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2058
2059            Pane::add_item(
2060                workspace,
2061                &pane,
2062                Box::new(cx.add_view(|_| item)),
2063                false,
2064                false,
2065                None,
2066                cx,
2067            );
2068        });
2069        assert_item_labels(&pane, ["buffer 1*"], cx);
2070
2071        // new singleton view with the same project entry
2072        workspace.update(cx, |workspace, cx| {
2073            let item = TestItem::new()
2074                .with_singleton(true)
2075                .with_label("buffer 1")
2076                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2077
2078            Pane::add_item(
2079                workspace,
2080                &pane,
2081                Box::new(cx.add_view(|_| item)),
2082                false,
2083                false,
2084                None,
2085                cx,
2086            );
2087        });
2088        assert_item_labels(&pane, ["buffer 1*"], cx);
2089
2090        // new singleton view with different project entry
2091        workspace.update(cx, |workspace, cx| {
2092            let item = TestItem::new()
2093                .with_singleton(true)
2094                .with_label("buffer 2")
2095                .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2096
2097            Pane::add_item(
2098                workspace,
2099                &pane,
2100                Box::new(cx.add_view(|_| item)),
2101                false,
2102                false,
2103                None,
2104                cx,
2105            );
2106        });
2107        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2108
2109        // new multibuffer view with the same project entry
2110        workspace.update(cx, |workspace, cx| {
2111            let item = TestItem::new()
2112                .with_singleton(false)
2113                .with_label("multibuffer 1")
2114                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2115
2116            Pane::add_item(
2117                workspace,
2118                &pane,
2119                Box::new(cx.add_view(|_| item)),
2120                false,
2121                false,
2122                None,
2123                cx,
2124            );
2125        });
2126        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2127
2128        // another multibuffer view with the same project entry
2129        workspace.update(cx, |workspace, cx| {
2130            let item = TestItem::new()
2131                .with_singleton(false)
2132                .with_label("multibuffer 1b")
2133                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2134
2135            Pane::add_item(
2136                workspace,
2137                &pane,
2138                Box::new(cx.add_view(|_| item)),
2139                false,
2140                false,
2141                None,
2142                cx,
2143            );
2144        });
2145        assert_item_labels(
2146            &pane,
2147            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2148            cx,
2149        );
2150    }
2151
2152    #[gpui::test]
2153    async fn test_remove_item_ordering(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2154        Settings::test_async(cx);
2155        let fs = FakeFs::new(cx.background());
2156
2157        let project = Project::test(fs, None, cx).await;
2158        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2159        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2160
2161        add_labled_item(&workspace, &pane, "A", cx);
2162        add_labled_item(&workspace, &pane, "B", cx);
2163        add_labled_item(&workspace, &pane, "C", cx);
2164        add_labled_item(&workspace, &pane, "D", cx);
2165        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2166
2167        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2168        add_labled_item(&workspace, &pane, "1", cx);
2169        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2170
2171        workspace.update(cx, |workspace, cx| {
2172            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2173        });
2174        deterministic.run_until_parked();
2175        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2176
2177        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2178        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2179
2180        workspace.update(cx, |workspace, cx| {
2181            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2182        });
2183        deterministic.run_until_parked();
2184        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2185
2186        workspace.update(cx, |workspace, cx| {
2187            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2188        });
2189        deterministic.run_until_parked();
2190        assert_item_labels(&pane, ["A", "C*"], cx);
2191
2192        workspace.update(cx, |workspace, cx| {
2193            Pane::close_active_item(workspace, &CloseActiveItem, cx);
2194        });
2195        deterministic.run_until_parked();
2196        assert_item_labels(&pane, ["A*"], cx);
2197    }
2198
2199    fn add_labled_item(
2200        workspace: &ViewHandle<Workspace>,
2201        pane: &ViewHandle<Pane>,
2202        label: &str,
2203        cx: &mut TestAppContext,
2204    ) -> Box<ViewHandle<TestItem>> {
2205        workspace.update(cx, |workspace, cx| {
2206            let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2207
2208            Pane::add_item(
2209                workspace,
2210                pane,
2211                labeled_item.clone(),
2212                false,
2213                false,
2214                None,
2215                cx,
2216            );
2217
2218            labeled_item
2219        })
2220    }
2221
2222    fn set_labeled_items<const COUNT: usize>(
2223        workspace: &ViewHandle<Workspace>,
2224        pane: &ViewHandle<Pane>,
2225        labels: [&str; COUNT],
2226        cx: &mut TestAppContext,
2227    ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2228        pane.update(cx, |pane, _| {
2229            pane.items.clear();
2230        });
2231
2232        workspace.update(cx, |workspace, cx| {
2233            let mut active_item_index = 0;
2234
2235            let mut index = 0;
2236            let items = labels.map(|mut label| {
2237                if label.ends_with("*") {
2238                    label = label.trim_end_matches("*");
2239                    active_item_index = index;
2240                }
2241
2242                let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2243                Pane::add_item(
2244                    workspace,
2245                    pane,
2246                    labeled_item.clone(),
2247                    false,
2248                    false,
2249                    None,
2250                    cx,
2251                );
2252                index += 1;
2253                labeled_item
2254            });
2255
2256            pane.update(cx, |pane, cx| {
2257                pane.activate_item(active_item_index, false, false, cx)
2258            });
2259
2260            items
2261        })
2262    }
2263
2264    // Assert the item label, with the active item label suffixed with a '*'
2265    fn assert_item_labels<const COUNT: usize>(
2266        pane: &ViewHandle<Pane>,
2267        expected_states: [&str; COUNT],
2268        cx: &mut TestAppContext,
2269    ) {
2270        pane.read_with(cx, |pane, cx| {
2271            let actual_states = pane
2272                .items
2273                .iter()
2274                .enumerate()
2275                .map(|(ix, item)| {
2276                    let mut state = item
2277                        .to_any()
2278                        .downcast::<TestItem>()
2279                        .unwrap()
2280                        .read(cx)
2281                        .label
2282                        .clone();
2283                    if ix == pane.active_item_index {
2284                        state.push('*');
2285                    }
2286                    state
2287                })
2288                .collect::<Vec<_>>();
2289
2290            assert_eq!(
2291                actual_states, expected_states,
2292                "pane items do not match expectation"
2293            );
2294        })
2295    }
2296}