pane.rs

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