pane.rs

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