pane.rs

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