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