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(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
 579        self.items.iter()
 580    }
 581
 582    pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
 583        self.items
 584            .iter()
 585            .filter_map(|item| item.to_any().downcast())
 586    }
 587
 588    pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
 589        self.items.get(self.active_item_index).cloned()
 590    }
 591
 592    pub fn item_for_entry(
 593        &self,
 594        entry_id: ProjectEntryId,
 595        cx: &AppContext,
 596    ) -> Option<Box<dyn ItemHandle>> {
 597        self.items.iter().find_map(|item| {
 598            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
 599                Some(item.boxed_clone())
 600            } else {
 601                None
 602            }
 603        })
 604    }
 605
 606    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
 607        self.items.iter().position(|i| i.id() == item.id())
 608    }
 609
 610    pub fn activate_item(
 611        &mut self,
 612        index: usize,
 613        activate_pane: bool,
 614        focus_item: bool,
 615        cx: &mut ViewContext<Self>,
 616    ) {
 617        use NavigationMode::{GoingBack, GoingForward};
 618        if index < self.items.len() {
 619            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
 620            if prev_active_item_ix != self.active_item_index
 621                || matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
 622            {
 623                if let Some(prev_item) = self.items.get(prev_active_item_ix) {
 624                    prev_item.deactivated(cx);
 625                }
 626                cx.emit(Event::ActivateItem {
 627                    local: activate_pane,
 628                });
 629            }
 630            self.update_toolbar(cx);
 631            if focus_item {
 632                self.focus_active_item(cx);
 633            }
 634            self.autoscroll = true;
 635            cx.notify();
 636        }
 637    }
 638
 639    pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
 640        let mut index = self.active_item_index;
 641        if index > 0 {
 642            index -= 1;
 643        } else if !self.items.is_empty() {
 644            index = self.items.len() - 1;
 645        }
 646        self.activate_item(index, activate_pane, activate_pane, cx);
 647    }
 648
 649    pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
 650        let mut index = self.active_item_index;
 651        if index + 1 < self.items.len() {
 652            index += 1;
 653        } else {
 654            index = 0;
 655        }
 656        self.activate_item(index, activate_pane, activate_pane, cx);
 657    }
 658
 659    pub fn close_active_item(
 660        workspace: &mut Workspace,
 661        _: &CloseActiveItem,
 662        cx: &mut ViewContext<Workspace>,
 663    ) -> Option<Task<Result<()>>> {
 664        let pane_handle = workspace.active_pane().clone();
 665        let pane = pane_handle.read(cx);
 666        if pane.items.is_empty() {
 667            None
 668        } else {
 669            let item_id_to_close = pane.items[pane.active_item_index].id();
 670            let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
 671                item_id == item_id_to_close
 672            });
 673            Some(cx.foreground().spawn(async move {
 674                task.await?;
 675                Ok(())
 676            }))
 677        }
 678    }
 679
 680    pub fn close_inactive_items(
 681        workspace: &mut Workspace,
 682        _: &CloseInactiveItems,
 683        cx: &mut ViewContext<Workspace>,
 684    ) -> Option<Task<Result<()>>> {
 685        let pane_handle = workspace.active_pane().clone();
 686        let pane = pane_handle.read(cx);
 687        if pane.items.is_empty() {
 688            None
 689        } else {
 690            let active_item_id = pane.items[pane.active_item_index].id();
 691            let task =
 692                Self::close_items(workspace, pane_handle, cx, move |id| id != active_item_id);
 693            Some(cx.foreground().spawn(async move {
 694                task.await?;
 695                Ok(())
 696            }))
 697        }
 698    }
 699
 700    pub fn close_item(
 701        workspace: &mut Workspace,
 702        pane: ViewHandle<Pane>,
 703        item_id_to_close: usize,
 704        cx: &mut ViewContext<Workspace>,
 705    ) -> Task<Result<()>> {
 706        Self::close_items(workspace, pane, cx, move |view_id| {
 707            view_id == item_id_to_close
 708        })
 709    }
 710
 711    pub fn close_items(
 712        workspace: &mut Workspace,
 713        pane: ViewHandle<Pane>,
 714        cx: &mut ViewContext<Workspace>,
 715        should_close: impl 'static + Fn(usize) -> bool,
 716    ) -> Task<Result<()>> {
 717        let project = workspace.project().clone();
 718
 719        // Find the items to close.
 720        let mut items_to_close = Vec::new();
 721        for item in &pane.read(cx).items {
 722            if should_close(item.id()) {
 723                items_to_close.push(item.boxed_clone());
 724            }
 725        }
 726
 727        // If a buffer is open both in a singleton editor and in a multibuffer, make sure
 728        // to focus the singleton buffer when prompting to save that buffer, as opposed
 729        // to focusing the multibuffer, because this gives the user a more clear idea
 730        // of what content they would be saving.
 731        items_to_close.sort_by_key(|item| !item.is_singleton(cx));
 732
 733        cx.spawn(|workspace, mut cx| async move {
 734            let mut saved_project_entry_ids = HashSet::default();
 735            for item in items_to_close.clone() {
 736                // Find the item's current index and its set of project entries. Avoid
 737                // storing these in advance, in case they have changed since this task
 738                // was started.
 739                let (item_ix, mut project_entry_ids) = pane.read_with(&cx, |pane, cx| {
 740                    (pane.index_for_item(&*item), item.project_entry_ids(cx))
 741                });
 742                let item_ix = if let Some(ix) = item_ix {
 743                    ix
 744                } else {
 745                    continue;
 746                };
 747
 748                // If an item hasn't yet been associated with a project entry, then always
 749                // prompt to save it before closing it. Otherwise, check if the item has
 750                // any project entries that are not open anywhere else in the workspace,
 751                // AND that the user has not already been prompted to save. If there are
 752                // any such project entries, prompt the user to save this item.
 753                let should_save = if project_entry_ids.is_empty() {
 754                    true
 755                } else {
 756                    workspace.read_with(&cx, |workspace, cx| {
 757                        for item in workspace.items(cx) {
 758                            if !items_to_close
 759                                .iter()
 760                                .any(|item_to_close| item_to_close.id() == item.id())
 761                            {
 762                                let other_project_entry_ids = item.project_entry_ids(cx);
 763                                project_entry_ids
 764                                    .retain(|id| !other_project_entry_ids.contains(id));
 765                            }
 766                        }
 767                    });
 768                    project_entry_ids
 769                        .iter()
 770                        .any(|id| saved_project_entry_ids.insert(*id))
 771                };
 772
 773                if should_save
 774                    && !Self::save_item(project.clone(), &pane, item_ix, &*item, true, &mut cx)
 775                        .await?
 776                {
 777                    break;
 778                }
 779
 780                // Remove the item from the pane.
 781                pane.update(&mut cx, |pane, cx| {
 782                    if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
 783                        pane.remove_item(item_ix, false, cx);
 784                    }
 785                });
 786            }
 787
 788            pane.update(&mut cx, |_, cx| cx.notify());
 789            Ok(())
 790        })
 791    }
 792
 793    fn remove_item(&mut self, item_ix: usize, activate_pane: bool, cx: &mut ViewContext<Self>) {
 794        if item_ix == self.active_item_index {
 795            // Activate the previous item if possible.
 796            // This returns the user to the previously opened tab if they closed
 797            // a new item they just navigated to.
 798            if item_ix > 0 {
 799                self.activate_prev_item(activate_pane, cx);
 800            } else if item_ix + 1 < self.items.len() {
 801                self.activate_next_item(activate_pane, cx);
 802            }
 803        }
 804
 805        let item = self.items.remove(item_ix);
 806        cx.emit(Event::RemoveItem { item_id: item.id() });
 807        if self.items.is_empty() {
 808            item.deactivated(cx);
 809            self.update_toolbar(cx);
 810            cx.emit(Event::Remove);
 811        }
 812
 813        if item_ix < self.active_item_index {
 814            self.active_item_index -= 1;
 815        }
 816
 817        self.nav_history
 818            .borrow_mut()
 819            .set_mode(NavigationMode::ClosingItem);
 820        item.deactivated(cx);
 821        self.nav_history
 822            .borrow_mut()
 823            .set_mode(NavigationMode::Normal);
 824
 825        if let Some(path) = item.project_path(cx) {
 826            self.nav_history
 827                .borrow_mut()
 828                .paths_by_item
 829                .insert(item.id(), path);
 830        } else {
 831            self.nav_history
 832                .borrow_mut()
 833                .paths_by_item
 834                .remove(&item.id());
 835        }
 836
 837        cx.notify();
 838    }
 839
 840    pub async fn save_item(
 841        project: ModelHandle<Project>,
 842        pane: &ViewHandle<Pane>,
 843        item_ix: usize,
 844        item: &dyn ItemHandle,
 845        should_prompt_for_save: bool,
 846        cx: &mut AsyncAppContext,
 847    ) -> Result<bool> {
 848        const CONFLICT_MESSAGE: &str =
 849            "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 850        const DIRTY_MESSAGE: &str = "This file contains unsaved edits. Do you want to save it?";
 851
 852        let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
 853            (
 854                item.has_conflict(cx),
 855                item.is_dirty(cx),
 856                item.can_save(cx),
 857                item.is_singleton(cx),
 858            )
 859        });
 860
 861        if has_conflict && can_save {
 862            let mut answer = pane.update(cx, |pane, cx| {
 863                pane.activate_item(item_ix, true, true, cx);
 864                cx.prompt(
 865                    PromptLevel::Warning,
 866                    CONFLICT_MESSAGE,
 867                    &["Overwrite", "Discard", "Cancel"],
 868                )
 869            });
 870            match answer.next().await {
 871                Some(0) => cx.update(|cx| item.save(project, cx)).await?,
 872                Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
 873                _ => return Ok(false),
 874            }
 875        } else if is_dirty && (can_save || is_singleton) {
 876            let will_autosave = cx.read(|cx| {
 877                matches!(
 878                    cx.global::<Settings>().autosave,
 879                    Autosave::OnFocusChange | Autosave::OnWindowChange
 880                ) && Self::can_autosave_item(&*item, cx)
 881            });
 882            let should_save = if should_prompt_for_save && !will_autosave {
 883                let mut answer = pane.update(cx, |pane, cx| {
 884                    pane.activate_item(item_ix, true, true, cx);
 885                    cx.prompt(
 886                        PromptLevel::Warning,
 887                        DIRTY_MESSAGE,
 888                        &["Save", "Don't Save", "Cancel"],
 889                    )
 890                });
 891                match answer.next().await {
 892                    Some(0) => true,
 893                    Some(1) => false,
 894                    _ => return Ok(false),
 895                }
 896            } else {
 897                true
 898            };
 899
 900            if should_save {
 901                if can_save {
 902                    cx.update(|cx| item.save(project, cx)).await?;
 903                } else if is_singleton {
 904                    let start_abs_path = project
 905                        .read_with(cx, |project, cx| {
 906                            let worktree = project.visible_worktrees(cx).next()?;
 907                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 908                        })
 909                        .unwrap_or_else(|| Path::new("").into());
 910
 911                    let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
 912                    if let Some(abs_path) = abs_path.next().await.flatten() {
 913                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
 914                    } else {
 915                        return Ok(false);
 916                    }
 917                }
 918            }
 919        }
 920        Ok(true)
 921    }
 922
 923    fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
 924        let is_deleted = item.project_entry_ids(cx).is_empty();
 925        item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
 926    }
 927
 928    pub fn autosave_item(
 929        item: &dyn ItemHandle,
 930        project: ModelHandle<Project>,
 931        cx: &mut MutableAppContext,
 932    ) -> Task<Result<()>> {
 933        if Self::can_autosave_item(item, cx) {
 934            item.save(project, cx)
 935        } else {
 936            Task::ready(Ok(()))
 937        }
 938    }
 939
 940    pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
 941        if let Some(active_item) = self.active_item() {
 942            cx.focus(active_item);
 943        }
 944    }
 945
 946    fn move_item(
 947        workspace: &mut Workspace,
 948        from: ViewHandle<Pane>,
 949        to: ViewHandle<Pane>,
 950        item_to_move: usize,
 951        destination_index: usize,
 952        cx: &mut ViewContext<Workspace>,
 953    ) {
 954        let item_to_move = from
 955            .read(cx)
 956            .items()
 957            .enumerate()
 958            .find(|(_, item_handle)| item_handle.id() == item_to_move);
 959
 960        if item_to_move.is_none() {
 961            log::warn!("Tried to move item handle which was not in `from` pane. Maybe tab was closed during drop");
 962            return;
 963        }
 964        let (item_ix, item_handle) = item_to_move.unwrap();
 965        let item_handle = item_handle.clone();
 966
 967        if from != to {
 968            // Close item from previous pane
 969            from.update(cx, |from, cx| {
 970                from.remove_item(item_ix, false, cx);
 971            });
 972        }
 973
 974        // This automatically removes duplicate items in the pane
 975        Pane::add_item(
 976            workspace,
 977            &to,
 978            item_handle,
 979            true,
 980            true,
 981            Some(destination_index),
 982            cx,
 983        );
 984
 985        cx.focus(to);
 986    }
 987
 988    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
 989        cx.emit(Event::Split(direction));
 990    }
 991
 992    fn deploy_split_menu(&mut self, action: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
 993        self.tab_bar_context_menu.update(cx, |menu, cx| {
 994            menu.show(
 995                action.position,
 996                AnchorCorner::TopRight,
 997                vec![
 998                    ContextMenuItem::item("Split Right", SplitRight),
 999                    ContextMenuItem::item("Split Left", SplitLeft),
1000                    ContextMenuItem::item("Split Up", SplitUp),
1001                    ContextMenuItem::item("Split Down", SplitDown),
1002                ],
1003                cx,
1004            );
1005        });
1006    }
1007
1008    fn deploy_dock_menu(&mut self, action: &DeployDockMenu, cx: &mut ViewContext<Self>) {
1009        self.tab_bar_context_menu.update(cx, |menu, cx| {
1010            menu.show(
1011                action.position,
1012                AnchorCorner::TopRight,
1013                vec![
1014                    ContextMenuItem::item("Anchor Dock Right", AnchorDockRight),
1015                    ContextMenuItem::item("Anchor Dock Bottom", AnchorDockBottom),
1016                    ContextMenuItem::item("Expand Dock", ExpandDock),
1017                ],
1018                cx,
1019            );
1020        });
1021    }
1022
1023    fn deploy_new_menu(&mut self, action: &DeployNewMenu, cx: &mut ViewContext<Self>) {
1024        self.tab_bar_context_menu.update(cx, |menu, cx| {
1025            menu.show(
1026                action.position,
1027                AnchorCorner::TopRight,
1028                vec![
1029                    ContextMenuItem::item("New File", NewFile),
1030                    ContextMenuItem::item("New Terminal", NewTerminal),
1031                    ContextMenuItem::item("New Search", NewSearch),
1032                ],
1033                cx,
1034            );
1035        });
1036    }
1037
1038    pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
1039        &self.toolbar
1040    }
1041
1042    fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1043        let active_item = self
1044            .items
1045            .get(self.active_item_index)
1046            .map(|item| item.as_ref());
1047        self.toolbar.update(cx, |toolbar, cx| {
1048            toolbar.set_active_pane_item(active_item, cx);
1049        });
1050    }
1051
1052    fn render_tabs(&mut self, cx: &mut RenderContext<Self>) -> impl Element {
1053        let theme = cx.global::<Settings>().theme.clone();
1054        let filler_index = self.items.len();
1055
1056        enum Tabs {}
1057        enum Tab {}
1058        enum Filler {}
1059        let pane = cx.handle();
1060        MouseEventHandler::<Tabs>::new(0, cx, |_, cx| {
1061            let autoscroll = if mem::take(&mut self.autoscroll) {
1062                Some(self.active_item_index)
1063            } else {
1064                None
1065            };
1066
1067            let pane_active = self.is_active;
1068
1069            let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
1070            for (ix, (item, detail)) in self
1071                .items
1072                .iter()
1073                .cloned()
1074                .zip(self.tab_details(cx))
1075                .enumerate()
1076            {
1077                let detail = if detail == 0 { None } else { Some(detail) };
1078                let tab_active = ix == self.active_item_index;
1079
1080                row.add_child({
1081                    MouseEventHandler::<Tab>::new(ix, cx, {
1082                        let item = item.clone();
1083                        let pane = pane.clone();
1084                        let detail = detail.clone();
1085
1086                        let theme = cx.global::<Settings>().theme.clone();
1087
1088                        move |mouse_state, cx| {
1089                            let tab_style =
1090                                theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1091                            let hovered = mouse_state.hovered;
1092                            Self::render_tab(
1093                                &item,
1094                                pane,
1095                                ix == 0,
1096                                detail,
1097                                hovered,
1098                                Self::tab_overlay_color(hovered, theme.as_ref(), cx),
1099                                tab_style,
1100                                cx,
1101                            )
1102                        }
1103                    })
1104                    .with_cursor_style(if pane_active && tab_active {
1105                        CursorStyle::Arrow
1106                    } else {
1107                        CursorStyle::PointingHand
1108                    })
1109                    .on_down(MouseButton::Left, move |_, cx| {
1110                        cx.dispatch_action(ActivateItem(ix));
1111                    })
1112                    .on_click(MouseButton::Middle, {
1113                        let item = item.clone();
1114                        let pane = pane.clone();
1115                        move |_, cx: &mut EventContext| {
1116                            cx.dispatch_action(CloseItem {
1117                                item_id: item.id(),
1118                                pane: pane.clone(),
1119                            })
1120                        }
1121                    })
1122                    .on_up(MouseButton::Left, {
1123                        let pane = pane.clone();
1124                        move |_, cx: &mut EventContext| Pane::handle_dropped_item(&pane, ix, cx)
1125                    })
1126                    .as_draggable(
1127                        DraggedItem {
1128                            item,
1129                            pane: pane.clone(),
1130                        },
1131                        {
1132                            let theme = cx.global::<Settings>().theme.clone();
1133
1134                            let detail = detail.clone();
1135                            move |dragged_item, cx: &mut RenderContext<Workspace>| {
1136                                let tab_style = &theme.workspace.tab_bar.dragged_tab;
1137                                Self::render_tab(
1138                                    &dragged_item.item,
1139                                    dragged_item.pane.clone(),
1140                                    false,
1141                                    detail,
1142                                    false,
1143                                    None,
1144                                    &tab_style,
1145                                    cx,
1146                                )
1147                            }
1148                        },
1149                    )
1150                    .boxed()
1151                })
1152            }
1153
1154            // Use the inactive tab style along with the current pane's active status to decide how to render
1155            // the filler
1156            let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1157            row.add_child(
1158                MouseEventHandler::<Filler>::new(0, cx, |mouse_state, cx| {
1159                    let mut filler = Empty::new()
1160                        .contained()
1161                        .with_style(filler_style.container)
1162                        .with_border(filler_style.container.border);
1163
1164                    if let Some(overlay) = Self::tab_overlay_color(mouse_state.hovered, &theme, cx)
1165                    {
1166                        filler = filler.with_overlay_color(overlay);
1167                    }
1168
1169                    filler.boxed()
1170                })
1171                .flex(1., true)
1172                .named("filler"),
1173            );
1174
1175            row.boxed()
1176        })
1177        .on_up(MouseButton::Left, move |_, cx| {
1178            Pane::handle_dropped_item(&pane, filler_index, cx)
1179        })
1180    }
1181
1182    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1183        let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1184
1185        let mut tab_descriptions = HashMap::default();
1186        let mut done = false;
1187        while !done {
1188            done = true;
1189
1190            // Store item indices by their tab description.
1191            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1192                if let Some(description) = item.tab_description(*detail, cx) {
1193                    if *detail == 0
1194                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1195                    {
1196                        tab_descriptions
1197                            .entry(description)
1198                            .or_insert(Vec::new())
1199                            .push(ix);
1200                    }
1201                }
1202            }
1203
1204            // If two or more items have the same tab description, increase their level
1205            // of detail and try again.
1206            for (_, item_ixs) in tab_descriptions.drain() {
1207                if item_ixs.len() > 1 {
1208                    done = false;
1209                    for ix in item_ixs {
1210                        tab_details[ix] += 1;
1211                    }
1212                }
1213            }
1214        }
1215
1216        tab_details
1217    }
1218
1219    fn render_tab<V: View>(
1220        item: &Box<dyn ItemHandle>,
1221        pane: WeakViewHandle<Pane>,
1222        first: bool,
1223        detail: Option<usize>,
1224        hovered: bool,
1225        overlay: Option<Color>,
1226        tab_style: &theme::Tab,
1227        cx: &mut RenderContext<V>,
1228    ) -> ElementBox {
1229        let title = item.tab_content(detail, &tab_style, cx);
1230        let mut container = tab_style.container.clone();
1231        if first {
1232            container.border.left = false;
1233        }
1234
1235        let mut tab = Flex::row()
1236            .with_child(
1237                Align::new({
1238                    let diameter = 7.0;
1239                    let icon_color = if item.has_conflict(cx) {
1240                        Some(tab_style.icon_conflict)
1241                    } else if item.is_dirty(cx) {
1242                        Some(tab_style.icon_dirty)
1243                    } else {
1244                        None
1245                    };
1246
1247                    ConstrainedBox::new(
1248                        Canvas::new(move |bounds, _, cx| {
1249                            if let Some(color) = icon_color {
1250                                let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1251                                cx.scene.push_quad(Quad {
1252                                    bounds: square,
1253                                    background: Some(color),
1254                                    border: Default::default(),
1255                                    corner_radius: diameter / 2.,
1256                                });
1257                            }
1258                        })
1259                        .boxed(),
1260                    )
1261                    .with_width(diameter)
1262                    .with_height(diameter)
1263                    .boxed()
1264                })
1265                .boxed(),
1266            )
1267            .with_child(
1268                Container::new(Align::new(title).boxed())
1269                    .with_style(ContainerStyle {
1270                        margin: Margin {
1271                            left: tab_style.spacing,
1272                            right: tab_style.spacing,
1273                            ..Default::default()
1274                        },
1275                        ..Default::default()
1276                    })
1277                    .boxed(),
1278            )
1279            .with_child(
1280                Align::new(
1281                    ConstrainedBox::new(if hovered {
1282                        let item_id = item.id();
1283                        enum TabCloseButton {}
1284                        let icon = Svg::new("icons/x_mark_thin_8.svg");
1285                        MouseEventHandler::<TabCloseButton>::new(item_id, cx, |mouse_state, _| {
1286                            if mouse_state.hovered {
1287                                icon.with_color(tab_style.icon_close_active).boxed()
1288                            } else {
1289                                icon.with_color(tab_style.icon_close).boxed()
1290                            }
1291                        })
1292                        .with_padding(Padding::uniform(4.))
1293                        .with_cursor_style(CursorStyle::PointingHand)
1294                        .on_click(MouseButton::Left, {
1295                            let pane = pane.clone();
1296                            move |_, cx| {
1297                                cx.dispatch_action(CloseItem {
1298                                    item_id,
1299                                    pane: pane.clone(),
1300                                })
1301                            }
1302                        })
1303                        .on_click(MouseButton::Middle, |_, cx| cx.propogate_event())
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    fn handle_dropped_item(pane: &WeakViewHandle<Pane>, index: usize, cx: &mut EventContext) {
1324        if let Some((_, dragged_item)) = cx
1325            .global::<DragAndDrop<Workspace>>()
1326            .currently_dragged::<DraggedItem>(cx.window_id)
1327        {
1328            cx.dispatch_action(MoveItem {
1329                item_id: dragged_item.item.id(),
1330                from: dragged_item.pane.clone(),
1331                to: pane.clone(),
1332                destination_index: index,
1333            })
1334        } else {
1335            cx.propogate_event();
1336        }
1337    }
1338
1339    fn tab_overlay_color(
1340        hovered: bool,
1341        theme: &Theme,
1342        cx: &mut RenderContext<Self>,
1343    ) -> Option<Color> {
1344        if hovered
1345            && cx
1346                .global::<DragAndDrop<Workspace>>()
1347                .currently_dragged::<DraggedItem>(cx.window_id())
1348                .is_some()
1349        {
1350            Some(theme.workspace.tab_bar.drop_target_overlay_color)
1351        } else {
1352            None
1353        }
1354    }
1355}
1356
1357impl Entity for Pane {
1358    type Event = Event;
1359}
1360
1361impl View for Pane {
1362    fn ui_name() -> &'static str {
1363        "Pane"
1364    }
1365
1366    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1367        let this = cx.handle();
1368
1369        enum MouseNavigationHandler {}
1370
1371        Stack::new()
1372            .with_child(
1373                MouseEventHandler::<MouseNavigationHandler>::new(0, cx, |_, cx| {
1374                    if let Some(active_item) = self.active_item() {
1375                        Flex::column()
1376                            .with_child({
1377                                let mut tab_row = Flex::row()
1378                                    .with_child(self.render_tabs(cx).flex(1.0, true).named("tabs"));
1379
1380                                // Render pane buttons
1381                                let theme = cx.global::<Settings>().theme.clone();
1382                                if self.is_active {
1383                                    tab_row.add_child(
1384                                        Flex::row()
1385                                            // New menu
1386                                            .with_child(tab_bar_button(
1387                                                0,
1388                                                "icons/plus_12.svg",
1389                                                cx,
1390                                                |position| DeployNewMenu { position },
1391                                            ))
1392                                            .with_child(
1393                                                self.docked
1394                                                    .map(|anchor| {
1395                                                        // Add the dock menu button if this pane is a dock
1396                                                        let dock_icon =
1397                                                            icon_for_dock_anchor(anchor);
1398
1399                                                        tab_bar_button(
1400                                                            1,
1401                                                            dock_icon,
1402                                                            cx,
1403                                                            |position| DeployDockMenu { position },
1404                                                        )
1405                                                    })
1406                                                    .unwrap_or_else(|| {
1407                                                        // Add the split menu if this pane is not a dock
1408                                                        tab_bar_button(
1409                                                            2,
1410                                                            "icons/split_12.svg",
1411                                                            cx,
1412                                                            |position| DeploySplitMenu { position },
1413                                                        )
1414                                                    }),
1415                                            )
1416                                            // Add the close dock button if this pane is a dock
1417                                            .with_children(self.docked.map(|_| {
1418                                                tab_bar_button(
1419                                                    3,
1420                                                    "icons/x_mark_thin_8.svg",
1421                                                    cx,
1422                                                    |_| HideDock,
1423                                                )
1424                                            }))
1425                                            .contained()
1426                                            .with_style(
1427                                                theme.workspace.tab_bar.pane_button_container,
1428                                            )
1429                                            .flex(1., false)
1430                                            .boxed(),
1431                                    )
1432                                }
1433
1434                                tab_row
1435                                    .constrained()
1436                                    .with_height(theme.workspace.tab_bar.height)
1437                                    .contained()
1438                                    .with_style(theme.workspace.tab_bar.container)
1439                                    .flex(1., false)
1440                                    .named("tab bar")
1441                            })
1442                            .with_child(ChildView::new(&self.toolbar, cx).expanded().boxed())
1443                            .with_child(ChildView::new(active_item, cx).flex(1., true).boxed())
1444                            .boxed()
1445                    } else {
1446                        enum EmptyPane {}
1447                        let theme = cx.global::<Settings>().theme.clone();
1448
1449                        MouseEventHandler::<EmptyPane>::new(0, cx, |_, _| {
1450                            Empty::new()
1451                                .contained()
1452                                .with_background_color(theme.workspace.background)
1453                                .boxed()
1454                        })
1455                        .on_down(MouseButton::Left, |_, cx| {
1456                            cx.focus_parent_view();
1457                        })
1458                        .on_up(MouseButton::Left, {
1459                            let pane = this.clone();
1460                            move |_, cx: &mut EventContext| Pane::handle_dropped_item(&pane, 0, cx)
1461                        })
1462                        .boxed()
1463                    }
1464                })
1465                .on_down(MouseButton::Navigate(NavigationDirection::Back), {
1466                    let this = this.clone();
1467                    move |_, cx| {
1468                        cx.dispatch_action(GoBack {
1469                            pane: Some(this.clone()),
1470                        });
1471                    }
1472                })
1473                .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1474                    let this = this.clone();
1475                    move |_, cx| {
1476                        cx.dispatch_action(GoForward {
1477                            pane: Some(this.clone()),
1478                        })
1479                    }
1480                })
1481                .boxed(),
1482            )
1483            .with_child(ChildView::new(&self.tab_bar_context_menu, cx).boxed())
1484            .named("pane")
1485    }
1486
1487    fn on_focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1488        if let Some(active_item) = self.active_item() {
1489            if cx.is_self_focused() {
1490                // Pane was focused directly. We need to either focus a view inside the active item,
1491                // or focus the active item itself
1492                if let Some(weak_last_focused_view) =
1493                    self.last_focused_view_by_item.get(&active_item.id())
1494                {
1495                    if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1496                        cx.focus(last_focused_view);
1497                        return;
1498                    } else {
1499                        self.last_focused_view_by_item.remove(&active_item.id());
1500                    }
1501                }
1502
1503                cx.focus(active_item);
1504            } else {
1505                self.last_focused_view_by_item
1506                    .insert(active_item.id(), focused.downgrade());
1507            }
1508        }
1509    }
1510}
1511
1512fn tab_bar_button<A: Action>(
1513    index: usize,
1514    icon: &'static str,
1515    cx: &mut RenderContext<Pane>,
1516    action_builder: impl 'static + Fn(Vector2F) -> A,
1517) -> ElementBox {
1518    enum TabBarButton {}
1519
1520    MouseEventHandler::<TabBarButton>::new(index, cx, |mouse_state, cx| {
1521        let theme = &cx.global::<Settings>().theme.workspace.tab_bar;
1522        let style = theme.pane_button.style_for(mouse_state, false);
1523        Svg::new(icon)
1524            .with_color(style.color)
1525            .constrained()
1526            .with_width(style.icon_width)
1527            .aligned()
1528            .constrained()
1529            .with_width(style.button_width)
1530            .with_height(style.button_width)
1531            // .aligned()
1532            .boxed()
1533    })
1534    .with_cursor_style(CursorStyle::PointingHand)
1535    .on_click(MouseButton::Left, move |e, cx| {
1536        cx.dispatch_action(action_builder(e.region.lower_right()));
1537    })
1538    .flex(1., false)
1539    .boxed()
1540}
1541
1542impl ItemNavHistory {
1543    pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut MutableAppContext) {
1544        self.history.borrow_mut().push(data, self.item.clone(), cx);
1545    }
1546
1547    pub fn pop_backward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1548        self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1549    }
1550
1551    pub fn pop_forward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1552        self.history
1553            .borrow_mut()
1554            .pop(NavigationMode::GoingForward, cx)
1555    }
1556}
1557
1558impl NavHistory {
1559    fn set_mode(&mut self, mode: NavigationMode) {
1560        self.mode = mode;
1561    }
1562
1563    fn disable(&mut self) {
1564        self.mode = NavigationMode::Disabled;
1565    }
1566
1567    fn enable(&mut self) {
1568        self.mode = NavigationMode::Normal;
1569    }
1570
1571    fn pop(&mut self, mode: NavigationMode, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1572        let entry = match mode {
1573            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1574                return None
1575            }
1576            NavigationMode::GoingBack => &mut self.backward_stack,
1577            NavigationMode::GoingForward => &mut self.forward_stack,
1578            NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1579        }
1580        .pop_back();
1581        if entry.is_some() {
1582            self.did_update(cx);
1583        }
1584        entry
1585    }
1586
1587    fn push<D: 'static + Any>(
1588        &mut self,
1589        data: Option<D>,
1590        item: Rc<dyn WeakItemHandle>,
1591        cx: &mut MutableAppContext,
1592    ) {
1593        match self.mode {
1594            NavigationMode::Disabled => {}
1595            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1596                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1597                    self.backward_stack.pop_front();
1598                }
1599                self.backward_stack.push_back(NavigationEntry {
1600                    item,
1601                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1602                });
1603                self.forward_stack.clear();
1604            }
1605            NavigationMode::GoingBack => {
1606                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1607                    self.forward_stack.pop_front();
1608                }
1609                self.forward_stack.push_back(NavigationEntry {
1610                    item,
1611                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1612                });
1613            }
1614            NavigationMode::GoingForward => {
1615                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1616                    self.backward_stack.pop_front();
1617                }
1618                self.backward_stack.push_back(NavigationEntry {
1619                    item,
1620                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1621                });
1622            }
1623            NavigationMode::ClosingItem => {
1624                if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1625                    self.closed_stack.pop_front();
1626                }
1627                self.closed_stack.push_back(NavigationEntry {
1628                    item,
1629                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1630                });
1631            }
1632        }
1633        self.did_update(cx);
1634    }
1635
1636    fn did_update(&self, cx: &mut MutableAppContext) {
1637        if let Some(pane) = self.pane.upgrade(cx) {
1638            cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1639        }
1640    }
1641}
1642
1643#[cfg(test)]
1644mod tests {
1645    use super::*;
1646    use crate::tests::TestItem;
1647    use gpui::TestAppContext;
1648    use project::FakeFs;
1649
1650    #[gpui::test]
1651    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
1652        cx.foreground().forbid_parking();
1653        Settings::test_async(cx);
1654        let fs = FakeFs::new(cx.background());
1655
1656        let project = Project::test(fs, None, cx).await;
1657        let (_, workspace) =
1658            cx.add_window(|cx| Workspace::new(project, |_, _| unimplemented!(), cx));
1659        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1660
1661        // 1. Add with a destination index
1662        //   a. Add before the active item
1663        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1664        workspace.update(cx, |workspace, cx| {
1665            Pane::add_item(
1666                workspace,
1667                &pane,
1668                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1669                false,
1670                false,
1671                Some(0),
1672                cx,
1673            );
1674        });
1675        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1676
1677        //   b. Add after the active item
1678        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1679        workspace.update(cx, |workspace, cx| {
1680            Pane::add_item(
1681                workspace,
1682                &pane,
1683                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1684                false,
1685                false,
1686                Some(2),
1687                cx,
1688            );
1689        });
1690        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1691
1692        //   c. Add at the end of the item list (including off the length)
1693        set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1694        workspace.update(cx, |workspace, cx| {
1695            Pane::add_item(
1696                workspace,
1697                &pane,
1698                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1699                false,
1700                false,
1701                Some(5),
1702                cx,
1703            );
1704        });
1705        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1706
1707        // 2. Add without a destination index
1708        //   a. Add with active item at the start of the item list
1709        set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1710        workspace.update(cx, |workspace, cx| {
1711            Pane::add_item(
1712                workspace,
1713                &pane,
1714                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1715                false,
1716                false,
1717                None,
1718                cx,
1719            );
1720        });
1721        set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
1722
1723        //   b. Add with active item at the end of the item list
1724        set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1725        workspace.update(cx, |workspace, cx| {
1726            Pane::add_item(
1727                workspace,
1728                &pane,
1729                Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1730                false,
1731                false,
1732                None,
1733                cx,
1734            );
1735        });
1736        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1737    }
1738
1739    #[gpui::test]
1740    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
1741        cx.foreground().forbid_parking();
1742        Settings::test_async(cx);
1743        let fs = FakeFs::new(cx.background());
1744
1745        let project = Project::test(fs, None, cx).await;
1746        let (_, workspace) =
1747            cx.add_window(|cx| Workspace::new(project, |_, _| unimplemented!(), cx));
1748        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1749
1750        // 1. Add with a destination index
1751        //   1a. Add before the active item
1752        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1753        workspace.update(cx, |workspace, cx| {
1754            Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
1755        });
1756        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1757
1758        //   1b. Add after the active item
1759        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1760        workspace.update(cx, |workspace, cx| {
1761            Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
1762        });
1763        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1764
1765        //   1c. Add at the end of the item list (including off the length)
1766        let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1767        workspace.update(cx, |workspace, cx| {
1768            Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
1769        });
1770        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1771
1772        //   1d. Add same item to active index
1773        let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1774        workspace.update(cx, |workspace, cx| {
1775            Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
1776        });
1777        assert_item_labels(&pane, ["A", "B*", "C"], cx);
1778
1779        //   1e. Add item to index after same item in last position
1780        let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1781        workspace.update(cx, |workspace, cx| {
1782            Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
1783        });
1784        assert_item_labels(&pane, ["A", "B", "C*"], cx);
1785
1786        // 2. Add without a destination index
1787        //   2a. Add with active item at the start of the item list
1788        let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
1789        workspace.update(cx, |workspace, cx| {
1790            Pane::add_item(workspace, &pane, d, false, false, None, cx);
1791        });
1792        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
1793
1794        //   2b. Add with active item at the end of the item list
1795        let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
1796        workspace.update(cx, |workspace, cx| {
1797            Pane::add_item(workspace, &pane, a, false, false, None, cx);
1798        });
1799        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1800
1801        //   2c. Add active item to active item at end of list
1802        let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1803        workspace.update(cx, |workspace, cx| {
1804            Pane::add_item(workspace, &pane, c, false, false, None, cx);
1805        });
1806        assert_item_labels(&pane, ["A", "B", "C*"], cx);
1807
1808        //   2d. Add active item to active item at start of list
1809        let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1810        workspace.update(cx, |workspace, cx| {
1811            Pane::add_item(workspace, &pane, a, false, false, None, cx);
1812        });
1813        assert_item_labels(&pane, ["A*", "B", "C"], cx);
1814    }
1815
1816    #[gpui::test]
1817    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
1818        cx.foreground().forbid_parking();
1819        Settings::test_async(cx);
1820        let fs = FakeFs::new(cx.background());
1821
1822        let project = Project::test(fs, None, cx).await;
1823        let (_, workspace) =
1824            cx.add_window(|cx| Workspace::new(project, |_, _| unimplemented!(), cx));
1825        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1826
1827        // singleton view
1828        workspace.update(cx, |workspace, cx| {
1829            let item = TestItem::new()
1830                .with_singleton(true)
1831                .with_label("buffer 1")
1832                .with_project_entry_ids(&[1]);
1833
1834            Pane::add_item(
1835                workspace,
1836                &pane,
1837                Box::new(cx.add_view(|_| item)),
1838                false,
1839                false,
1840                None,
1841                cx,
1842            );
1843        });
1844        assert_item_labels(&pane, ["buffer 1*"], cx);
1845
1846        // new singleton view with the same project entry
1847        workspace.update(cx, |workspace, cx| {
1848            let item = TestItem::new()
1849                .with_singleton(true)
1850                .with_label("buffer 1")
1851                .with_project_entry_ids(&[1]);
1852
1853            Pane::add_item(
1854                workspace,
1855                &pane,
1856                Box::new(cx.add_view(|_| item)),
1857                false,
1858                false,
1859                None,
1860                cx,
1861            );
1862        });
1863        assert_item_labels(&pane, ["buffer 1*"], cx);
1864
1865        // new singleton view with different project entry
1866        workspace.update(cx, |workspace, cx| {
1867            let item = TestItem::new()
1868                .with_singleton(true)
1869                .with_label("buffer 2")
1870                .with_project_entry_ids(&[2]);
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", "buffer 2*"], cx);
1883
1884        // new multibuffer view with the same project entry
1885        workspace.update(cx, |workspace, cx| {
1886            let item = TestItem::new()
1887                .with_singleton(false)
1888                .with_label("multibuffer 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", "buffer 2", "multibuffer 1*"], cx);
1902
1903        // another multibuffer view with the same project entry
1904        workspace.update(cx, |workspace, cx| {
1905            let item = TestItem::new()
1906                .with_singleton(false)
1907                .with_label("multibuffer 1b")
1908                .with_project_entry_ids(&[1]);
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(
1921            &pane,
1922            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
1923            cx,
1924        );
1925    }
1926
1927    fn set_labeled_items<const COUNT: usize>(
1928        workspace: &ViewHandle<Workspace>,
1929        pane: &ViewHandle<Pane>,
1930        labels: [&str; COUNT],
1931        cx: &mut TestAppContext,
1932    ) -> [Box<ViewHandle<TestItem>>; COUNT] {
1933        pane.update(cx, |pane, _| {
1934            pane.items.clear();
1935        });
1936
1937        workspace.update(cx, |workspace, cx| {
1938            let mut active_item_index = 0;
1939
1940            let mut index = 0;
1941            let items = labels.map(|mut label| {
1942                if label.ends_with("*") {
1943                    label = label.trim_end_matches("*");
1944                    active_item_index = index;
1945                }
1946
1947                let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
1948                Pane::add_item(
1949                    workspace,
1950                    pane,
1951                    labeled_item.clone(),
1952                    false,
1953                    false,
1954                    None,
1955                    cx,
1956                );
1957                index += 1;
1958                labeled_item
1959            });
1960
1961            pane.update(cx, |pane, cx| {
1962                pane.activate_item(active_item_index, false, false, cx)
1963            });
1964
1965            items
1966        })
1967    }
1968
1969    // Assert the item label, with the active item label suffixed with a '*'
1970    fn assert_item_labels<const COUNT: usize>(
1971        pane: &ViewHandle<Pane>,
1972        expected_states: [&str; COUNT],
1973        cx: &mut TestAppContext,
1974    ) {
1975        pane.read_with(cx, |pane, cx| {
1976            let actual_states = pane
1977                .items
1978                .iter()
1979                .enumerate()
1980                .map(|(ix, item)| {
1981                    let mut state = item
1982                        .to_any()
1983                        .downcast::<TestItem>()
1984                        .unwrap()
1985                        .read(cx)
1986                        .label
1987                        .clone();
1988                    if ix == pane.active_item_index {
1989                        state.push('*');
1990                    }
1991                    state
1992                })
1993                .collect::<Vec<_>>();
1994
1995            assert_eq!(
1996                actual_states, expected_states,
1997                "pane items do not match expectation"
1998            );
1999        })
2000    }
2001}