pane.rs

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