pane.rs

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