pane.rs

   1use super::{ItemHandle, SplitDirection};
   2use crate::{toolbar::Toolbar, Item, NewFile, NewSearch, NewTerminal, WeakItemHandle, Workspace};
   3use anyhow::Result;
   4use collections::{HashMap, HashSet, VecDeque};
   5use context_menu::{ContextMenu, ContextMenuItem};
   6use futures::StreamExt;
   7use gpui::{
   8    actions,
   9    elements::*,
  10    geometry::{
  11        rect::RectF,
  12        vector::{vec2f, Vector2F},
  13    },
  14    impl_actions, impl_internal_actions,
  15    platform::{CursorStyle, NavigationDirection},
  16    AnyViewHandle, AnyWeakViewHandle, AppContext, AsyncAppContext, Entity, EventContext,
  17    ModelHandle, MouseButton, MouseButtonEvent, MutableAppContext, PromptLevel, Quad,
  18    RenderContext, Task, View, ViewContext, ViewHandle, WeakViewHandle,
  19};
  20use project::{Project, ProjectEntryId, ProjectPath};
  21use serde::Deserialize;
  22use settings::{Autosave, Settings};
  23use std::{any::Any, cell::RefCell, mem, path::Path, rc::Rc};
  24use util::ResultExt;
  25
  26#[derive(Clone, Deserialize, PartialEq)]
  27pub struct ActivateItem(pub usize);
  28
  29actions!(
  30    pane,
  31    [
  32        ActivatePrevItem,
  33        ActivateNextItem,
  34        ActivateLastItem,
  35        CloseActiveItem,
  36        CloseInactiveItems,
  37        ReopenClosedItem,
  38        SplitLeft,
  39        SplitUp,
  40        SplitRight,
  41        SplitDown,
  42    ]
  43);
  44
  45#[derive(Clone, PartialEq)]
  46pub struct CloseItem {
  47    pub item_id: usize,
  48    pub pane: WeakViewHandle<Pane>,
  49}
  50
  51#[derive(Clone, Deserialize, PartialEq)]
  52pub struct GoBack {
  53    #[serde(skip_deserializing)]
  54    pub pane: Option<WeakViewHandle<Pane>>,
  55}
  56
  57#[derive(Clone, Deserialize, PartialEq)]
  58pub struct GoForward {
  59    #[serde(skip_deserializing)]
  60    pub pane: Option<WeakViewHandle<Pane>>,
  61}
  62
  63#[derive(Clone, PartialEq)]
  64pub struct DeploySplitMenu {
  65    position: Vector2F,
  66}
  67
  68#[derive(Clone, PartialEq)]
  69pub struct DeployNewMenu {
  70    position: Vector2F,
  71}
  72
  73impl_actions!(pane, [GoBack, GoForward, ActivateItem]);
  74impl_internal_actions!(pane, [CloseItem, DeploySplitMenu, DeployNewMenu]);
  75
  76const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
  77
  78pub fn init(cx: &mut MutableAppContext) {
  79    cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
  80        pane.activate_item(action.0, true, true, false, cx);
  81    });
  82    cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
  83        pane.activate_item(pane.items.len() - 1, true, true, false, cx);
  84    });
  85    cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
  86        pane.activate_prev_item(cx);
  87    });
  88    cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
  89        pane.activate_next_item(cx);
  90    });
  91    cx.add_async_action(Pane::close_active_item);
  92    cx.add_async_action(Pane::close_inactive_items);
  93    cx.add_async_action(|workspace: &mut Workspace, action: &CloseItem, cx| {
  94        let pane = action.pane.upgrade(cx)?;
  95        let task = Pane::close_item(workspace, pane, action.item_id, cx);
  96        Some(cx.foreground().spawn(async move {
  97            task.await?;
  98            Ok(())
  99        }))
 100    });
 101    cx.add_action(|pane: &mut Pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx));
 102    cx.add_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx));
 103    cx.add_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx));
 104    cx.add_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx));
 105    cx.add_action(Pane::deploy_split_menu);
 106    cx.add_action(Pane::deploy_new_menu);
 107    cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
 108        Pane::reopen_closed_item(workspace, cx).detach();
 109    });
 110    cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
 111        Pane::go_back(
 112            workspace,
 113            action
 114                .pane
 115                .as_ref()
 116                .and_then(|weak_handle| weak_handle.upgrade(cx)),
 117            cx,
 118        )
 119        .detach();
 120    });
 121    cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
 122        Pane::go_forward(
 123            workspace,
 124            action
 125                .pane
 126                .as_ref()
 127                .and_then(|weak_handle| weak_handle.upgrade(cx)),
 128            cx,
 129        )
 130        .detach();
 131    });
 132}
 133
 134pub enum Event {
 135    Focused,
 136    ActivateItem { local: bool },
 137    Remove,
 138    RemoveItem,
 139    Split(SplitDirection),
 140    ChangeItemTitle,
 141}
 142
 143pub struct Pane {
 144    items: Vec<Box<dyn ItemHandle>>,
 145    is_active: bool,
 146    active_item_index: usize,
 147    last_focused_view: Option<AnyWeakViewHandle>,
 148    autoscroll: bool,
 149    nav_history: Rc<RefCell<NavHistory>>,
 150    toolbar: ViewHandle<Toolbar>,
 151    context_menu: ViewHandle<ContextMenu>,
 152}
 153
 154pub struct ItemNavHistory {
 155    history: Rc<RefCell<NavHistory>>,
 156    item: Rc<dyn WeakItemHandle>,
 157}
 158
 159struct NavHistory {
 160    mode: NavigationMode,
 161    backward_stack: VecDeque<NavigationEntry>,
 162    forward_stack: VecDeque<NavigationEntry>,
 163    closed_stack: VecDeque<NavigationEntry>,
 164    paths_by_item: HashMap<usize, ProjectPath>,
 165    pane: WeakViewHandle<Pane>,
 166}
 167
 168#[derive(Copy, Clone)]
 169enum NavigationMode {
 170    Normal,
 171    GoingBack,
 172    GoingForward,
 173    ClosingItem,
 174    ReopeningClosedItem,
 175    Disabled,
 176}
 177
 178impl Default for NavigationMode {
 179    fn default() -> Self {
 180        Self::Normal
 181    }
 182}
 183
 184pub struct NavigationEntry {
 185    pub item: Rc<dyn WeakItemHandle>,
 186    pub data: Option<Box<dyn Any>>,
 187}
 188
 189impl Pane {
 190    pub fn new(cx: &mut ViewContext<Self>) -> Self {
 191        let handle = cx.weak_handle();
 192        let context_menu = cx.add_view(ContextMenu::new);
 193        Self {
 194            items: Vec::new(),
 195            is_active: true,
 196            active_item_index: 0,
 197            last_focused_view: None,
 198            autoscroll: false,
 199            nav_history: Rc::new(RefCell::new(NavHistory {
 200                mode: NavigationMode::Normal,
 201                backward_stack: Default::default(),
 202                forward_stack: Default::default(),
 203                closed_stack: Default::default(),
 204                paths_by_item: Default::default(),
 205                pane: handle.clone(),
 206            })),
 207            toolbar: cx.add_view(|_| Toolbar::new(handle)),
 208            context_menu,
 209        }
 210    }
 211
 212    pub fn set_active(&mut self, is_active: bool, cx: &mut ViewContext<Self>) {
 213        self.is_active = is_active;
 214        cx.notify();
 215    }
 216
 217    pub fn nav_history_for_item<T: Item>(&self, item: &ViewHandle<T>) -> ItemNavHistory {
 218        ItemNavHistory {
 219            history: self.nav_history.clone(),
 220            item: Rc::new(item.downgrade()),
 221        }
 222    }
 223
 224    pub fn go_back(
 225        workspace: &mut Workspace,
 226        pane: Option<ViewHandle<Pane>>,
 227        cx: &mut ViewContext<Workspace>,
 228    ) -> Task<()> {
 229        Self::navigate_history(
 230            workspace,
 231            pane.unwrap_or_else(|| workspace.active_pane().clone()),
 232            NavigationMode::GoingBack,
 233            cx,
 234        )
 235    }
 236
 237    pub fn go_forward(
 238        workspace: &mut Workspace,
 239        pane: Option<ViewHandle<Pane>>,
 240        cx: &mut ViewContext<Workspace>,
 241    ) -> Task<()> {
 242        Self::navigate_history(
 243            workspace,
 244            pane.unwrap_or_else(|| workspace.active_pane().clone()),
 245            NavigationMode::GoingForward,
 246            cx,
 247        )
 248    }
 249
 250    pub fn reopen_closed_item(
 251        workspace: &mut Workspace,
 252        cx: &mut ViewContext<Workspace>,
 253    ) -> Task<()> {
 254        Self::navigate_history(
 255            workspace,
 256            workspace.active_pane().clone(),
 257            NavigationMode::ReopeningClosedItem,
 258            cx,
 259        )
 260    }
 261
 262    pub fn disable_history(&mut self) {
 263        self.nav_history.borrow_mut().disable();
 264    }
 265
 266    pub fn enable_history(&mut self) {
 267        self.nav_history.borrow_mut().enable();
 268    }
 269
 270    pub fn can_navigate_backward(&self) -> bool {
 271        !self.nav_history.borrow().backward_stack.is_empty()
 272    }
 273
 274    pub fn can_navigate_forward(&self) -> bool {
 275        !self.nav_history.borrow().forward_stack.is_empty()
 276    }
 277
 278    fn history_updated(&mut self, cx: &mut ViewContext<Self>) {
 279        self.toolbar.update(cx, |_, cx| cx.notify());
 280    }
 281
 282    fn navigate_history(
 283        workspace: &mut Workspace,
 284        pane: ViewHandle<Pane>,
 285        mode: NavigationMode,
 286        cx: &mut ViewContext<Workspace>,
 287    ) -> Task<()> {
 288        cx.focus(pane.clone());
 289
 290        let to_load = pane.update(cx, |pane, cx| {
 291            loop {
 292                // Retrieve the weak item handle from the history.
 293                let entry = pane.nav_history.borrow_mut().pop(mode, cx)?;
 294
 295                // If the item is still present in this pane, then activate it.
 296                if let Some(index) = entry
 297                    .item
 298                    .upgrade(cx)
 299                    .and_then(|v| pane.index_for_item(v.as_ref()))
 300                {
 301                    let prev_active_item_index = pane.active_item_index;
 302                    pane.nav_history.borrow_mut().set_mode(mode);
 303                    pane.activate_item(index, true, true, false, cx);
 304                    pane.nav_history
 305                        .borrow_mut()
 306                        .set_mode(NavigationMode::Normal);
 307
 308                    let mut navigated = prev_active_item_index != pane.active_item_index;
 309                    if let Some(data) = entry.data {
 310                        navigated |= pane.active_item()?.navigate(data, cx);
 311                    }
 312
 313                    if navigated {
 314                        break None;
 315                    }
 316                }
 317                // If the item is no longer present in this pane, then retrieve its
 318                // project path in order to reopen it.
 319                else {
 320                    break pane
 321                        .nav_history
 322                        .borrow()
 323                        .paths_by_item
 324                        .get(&entry.item.id())
 325                        .cloned()
 326                        .map(|project_path| (project_path, entry));
 327                }
 328            }
 329        });
 330
 331        if let Some((project_path, entry)) = to_load {
 332            // If the item was no longer present, then load it again from its previous path.
 333            let pane = pane.downgrade();
 334            let task = workspace.load_path(project_path, cx);
 335            cx.spawn(|workspace, mut cx| async move {
 336                let task = task.await;
 337                if let Some(pane) = pane.upgrade(&cx) {
 338                    let mut navigated = false;
 339                    if let Some((project_entry_id, build_item)) = task.log_err() {
 340                        let prev_active_item_id = pane.update(&mut cx, |pane, _| {
 341                            pane.nav_history.borrow_mut().set_mode(mode);
 342                            pane.active_item().map(|p| p.id())
 343                        });
 344
 345                        let item = workspace.update(&mut cx, |workspace, cx| {
 346                            Self::open_item(
 347                                workspace,
 348                                pane.clone(),
 349                                project_entry_id,
 350                                true,
 351                                cx,
 352                                build_item,
 353                            )
 354                        });
 355
 356                        pane.update(&mut cx, |pane, cx| {
 357                            navigated |= Some(item.id()) != prev_active_item_id;
 358                            pane.nav_history
 359                                .borrow_mut()
 360                                .set_mode(NavigationMode::Normal);
 361                            if let Some(data) = entry.data {
 362                                navigated |= item.navigate(data, cx);
 363                            }
 364                        });
 365                    }
 366
 367                    if !navigated {
 368                        workspace
 369                            .update(&mut cx, |workspace, cx| {
 370                                Self::navigate_history(workspace, pane, mode, cx)
 371                            })
 372                            .await;
 373                    }
 374                }
 375            })
 376        } else {
 377            Task::ready(())
 378        }
 379    }
 380
 381    pub(crate) fn open_item(
 382        workspace: &mut Workspace,
 383        pane: ViewHandle<Pane>,
 384        project_entry_id: ProjectEntryId,
 385        focus_item: bool,
 386        cx: &mut ViewContext<Workspace>,
 387        build_item: impl FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
 388    ) -> Box<dyn ItemHandle> {
 389        let existing_item = pane.update(cx, |pane, cx| {
 390            for (ix, item) in pane.items.iter().enumerate() {
 391                if item.project_path(cx).is_some()
 392                    && item.project_entry_ids(cx).as_slice() == [project_entry_id]
 393                {
 394                    let item = item.boxed_clone();
 395                    pane.activate_item(ix, true, focus_item, true, cx);
 396                    return Some(item);
 397                }
 398            }
 399            None
 400        });
 401        if let Some(existing_item) = existing_item {
 402            existing_item
 403        } else {
 404            let item = pane.update(cx, |_, cx| build_item(cx));
 405            Self::add_item(workspace, pane, item.boxed_clone(), true, focus_item, cx);
 406            item
 407        }
 408    }
 409
 410    pub(crate) fn add_item(
 411        workspace: &mut Workspace,
 412        pane: ViewHandle<Pane>,
 413        item: Box<dyn ItemHandle>,
 414        activate_pane: bool,
 415        focus_item: bool,
 416        cx: &mut ViewContext<Workspace>,
 417    ) {
 418        // Prevent adding the same item to the pane more than once.
 419        // If there is already an active item, reorder the desired item to be after it
 420        // and activate it.
 421        if let Some(item_ix) = pane.read(cx).items.iter().position(|i| i.id() == item.id()) {
 422            pane.update(cx, |pane, cx| {
 423                pane.activate_item(item_ix, activate_pane, focus_item, true, cx)
 424            });
 425            return;
 426        }
 427
 428        item.added_to_pane(workspace, pane.clone(), cx);
 429        pane.update(cx, |pane, cx| {
 430            // If there is already an active item, then insert the new item
 431            // right after it. Otherwise, adjust the `active_item_index` field
 432            // before activating the new item, so that in the `activate_item`
 433            // method, we can detect that the active item is changing.
 434            let item_ix;
 435            if pane.active_item_index < pane.items.len() {
 436                item_ix = pane.active_item_index + 1
 437            } else {
 438                item_ix = pane.items.len();
 439                pane.active_item_index = usize::MAX;
 440            };
 441
 442            cx.reparent(&item);
 443            pane.items.insert(item_ix, item);
 444            pane.activate_item(item_ix, activate_pane, focus_item, false, cx);
 445            cx.notify();
 446        });
 447    }
 448
 449    pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
 450        self.items.iter()
 451    }
 452
 453    pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
 454        self.items
 455            .iter()
 456            .filter_map(|item| item.to_any().downcast())
 457    }
 458
 459    pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
 460        self.items.get(self.active_item_index).cloned()
 461    }
 462
 463    pub fn item_for_entry(
 464        &self,
 465        entry_id: ProjectEntryId,
 466        cx: &AppContext,
 467    ) -> Option<Box<dyn ItemHandle>> {
 468        self.items.iter().find_map(|item| {
 469            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
 470                Some(item.boxed_clone())
 471            } else {
 472                None
 473            }
 474        })
 475    }
 476
 477    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
 478        self.items.iter().position(|i| i.id() == item.id())
 479    }
 480
 481    pub fn activate_item(
 482        &mut self,
 483        mut index: usize,
 484        activate_pane: bool,
 485        focus_item: bool,
 486        move_after_current_active: bool,
 487        cx: &mut ViewContext<Self>,
 488    ) {
 489        use NavigationMode::{GoingBack, GoingForward};
 490        if index < self.items.len() {
 491            if move_after_current_active {
 492                // If there is already an active item, reorder the desired item to be after it
 493                // and activate it.
 494                if self.active_item_index != index && self.active_item_index < self.items.len() {
 495                    let pane_to_activate = self.items.remove(index);
 496                    if self.active_item_index < index {
 497                        index = self.active_item_index + 1;
 498                    } else if self.active_item_index < self.items.len() + 1 {
 499                        index = self.active_item_index;
 500                        // Index is less than active_item_index. Reordering will decrement the
 501                        // active_item_index, so adjust it accordingly
 502                        self.active_item_index = index - 1;
 503                    }
 504                    self.items.insert(index, pane_to_activate);
 505                }
 506            }
 507
 508            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
 509            if prev_active_item_ix != self.active_item_index
 510                || matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
 511            {
 512                if let Some(prev_item) = self.items.get(prev_active_item_ix) {
 513                    prev_item.deactivated(cx);
 514                }
 515                cx.emit(Event::ActivateItem {
 516                    local: activate_pane,
 517                });
 518            }
 519            self.update_toolbar(cx);
 520            if focus_item {
 521                self.focus_active_item(cx);
 522            }
 523            if activate_pane {
 524                cx.emit(Event::Focused);
 525            }
 526            self.autoscroll = true;
 527            cx.notify();
 528        }
 529    }
 530
 531    pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
 532        let mut index = self.active_item_index;
 533        if index > 0 {
 534            index -= 1;
 535        } else if !self.items.is_empty() {
 536            index = self.items.len() - 1;
 537        }
 538        self.activate_item(index, true, true, false, cx);
 539    }
 540
 541    pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
 542        let mut index = self.active_item_index;
 543        if index + 1 < self.items.len() {
 544            index += 1;
 545        } else {
 546            index = 0;
 547        }
 548        self.activate_item(index, true, true, false, cx);
 549    }
 550
 551    pub fn close_active_item(
 552        workspace: &mut Workspace,
 553        _: &CloseActiveItem,
 554        cx: &mut ViewContext<Workspace>,
 555    ) -> Option<Task<Result<()>>> {
 556        let pane_handle = workspace.active_pane().clone();
 557        let pane = pane_handle.read(cx);
 558        if pane.items.is_empty() {
 559            None
 560        } else {
 561            let item_id_to_close = pane.items[pane.active_item_index].id();
 562            let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
 563                item_id == item_id_to_close
 564            });
 565            Some(cx.foreground().spawn(async move {
 566                task.await?;
 567                Ok(())
 568            }))
 569        }
 570    }
 571
 572    pub fn close_inactive_items(
 573        workspace: &mut Workspace,
 574        _: &CloseInactiveItems,
 575        cx: &mut ViewContext<Workspace>,
 576    ) -> Option<Task<Result<()>>> {
 577        let pane_handle = workspace.active_pane().clone();
 578        let pane = pane_handle.read(cx);
 579        if pane.items.is_empty() {
 580            None
 581        } else {
 582            let active_item_id = pane.items[pane.active_item_index].id();
 583            let task =
 584                Self::close_items(workspace, pane_handle, cx, move |id| id != active_item_id);
 585            Some(cx.foreground().spawn(async move {
 586                task.await?;
 587                Ok(())
 588            }))
 589        }
 590    }
 591
 592    pub fn close_item(
 593        workspace: &mut Workspace,
 594        pane: ViewHandle<Pane>,
 595        item_id_to_close: usize,
 596        cx: &mut ViewContext<Workspace>,
 597    ) -> Task<Result<bool>> {
 598        Self::close_items(workspace, pane, cx, move |view_id| {
 599            view_id == item_id_to_close
 600        })
 601    }
 602
 603    pub fn close_items(
 604        workspace: &mut Workspace,
 605        pane: ViewHandle<Pane>,
 606        cx: &mut ViewContext<Workspace>,
 607        should_close: impl 'static + Fn(usize) -> bool,
 608    ) -> Task<Result<bool>> {
 609        let project = workspace.project().clone();
 610
 611        // Find the items to close.
 612        let mut items_to_close = Vec::new();
 613        for item in &pane.read(cx).items {
 614            if should_close(item.id()) {
 615                items_to_close.push(item.boxed_clone());
 616            }
 617        }
 618
 619        // If a buffer is open both in a singleton editor and in a multibuffer, make sure
 620        // to focus the singleton buffer when prompting to save that buffer, as opposed
 621        // to focusing the multibuffer, because this gives the user a more clear idea
 622        // of what content they would be saving.
 623        items_to_close.sort_by_key(|item| !item.is_singleton(cx));
 624
 625        cx.spawn(|workspace, mut cx| async move {
 626            let mut saved_project_entry_ids = HashSet::default();
 627            for item in items_to_close.clone() {
 628                // Find the item's current index and its set of project entries. Avoid
 629                // storing these in advance, in case they have changed since this task
 630                // was started.
 631                let (item_ix, mut project_entry_ids) = pane.read_with(&cx, |pane, cx| {
 632                    (pane.index_for_item(&*item), item.project_entry_ids(cx))
 633                });
 634                let item_ix = if let Some(ix) = item_ix {
 635                    ix
 636                } else {
 637                    continue;
 638                };
 639
 640                // If an item hasn't yet been associated with a project entry, then always
 641                // prompt to save it before closing it. Otherwise, check if the item has
 642                // any project entries that are not open anywhere else in the workspace,
 643                // AND that the user has not already been prompted to save. If there are
 644                // any such project entries, prompt the user to save this item.
 645                let should_save = if project_entry_ids.is_empty() {
 646                    true
 647                } else {
 648                    workspace.read_with(&cx, |workspace, cx| {
 649                        for item in workspace.items(cx) {
 650                            if !items_to_close
 651                                .iter()
 652                                .any(|item_to_close| item_to_close.id() == item.id())
 653                            {
 654                                let other_project_entry_ids = item.project_entry_ids(cx);
 655                                project_entry_ids
 656                                    .retain(|id| !other_project_entry_ids.contains(id));
 657                            }
 658                        }
 659                    });
 660                    project_entry_ids
 661                        .iter()
 662                        .any(|id| saved_project_entry_ids.insert(*id))
 663                };
 664
 665                if should_save
 666                    && !Self::save_item(project.clone(), &pane, item_ix, &*item, true, &mut cx)
 667                        .await?
 668                {
 669                    break;
 670                }
 671
 672                // Remove the item from the pane.
 673                pane.update(&mut cx, |pane, cx| {
 674                    if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
 675                        if item_ix == pane.active_item_index {
 676                            // Activate the previous item if possible.
 677                            // This returns the user to the previously opened tab if they closed
 678                            // a ne item they just navigated to.
 679                            if item_ix > 0 {
 680                                pane.activate_prev_item(cx);
 681                            } else if item_ix + 1 < pane.items.len() {
 682                                pane.activate_next_item(cx);
 683                            }
 684                        }
 685
 686                        let item = pane.items.remove(item_ix);
 687                        cx.emit(Event::RemoveItem);
 688                        if pane.items.is_empty() {
 689                            item.deactivated(cx);
 690                            pane.update_toolbar(cx);
 691                            cx.emit(Event::Remove);
 692                        }
 693
 694                        if item_ix < pane.active_item_index {
 695                            pane.active_item_index -= 1;
 696                        }
 697
 698                        pane.nav_history
 699                            .borrow_mut()
 700                            .set_mode(NavigationMode::ClosingItem);
 701                        item.deactivated(cx);
 702                        pane.nav_history
 703                            .borrow_mut()
 704                            .set_mode(NavigationMode::Normal);
 705
 706                        if let Some(path) = item.project_path(cx) {
 707                            pane.nav_history
 708                                .borrow_mut()
 709                                .paths_by_item
 710                                .insert(item.id(), path);
 711                        } else {
 712                            pane.nav_history
 713                                .borrow_mut()
 714                                .paths_by_item
 715                                .remove(&item.id());
 716                        }
 717                    }
 718                });
 719            }
 720
 721            pane.update(&mut cx, |_, cx| cx.notify());
 722            Ok(true)
 723        })
 724    }
 725
 726    pub async fn save_item(
 727        project: ModelHandle<Project>,
 728        pane: &ViewHandle<Pane>,
 729        item_ix: usize,
 730        item: &dyn ItemHandle,
 731        should_prompt_for_save: bool,
 732        cx: &mut AsyncAppContext,
 733    ) -> Result<bool> {
 734        const CONFLICT_MESSAGE: &str =
 735            "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 736        const DIRTY_MESSAGE: &str = "This file contains unsaved edits. Do you want to save it?";
 737
 738        let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
 739            (
 740                item.has_conflict(cx),
 741                item.is_dirty(cx),
 742                item.can_save(cx),
 743                item.is_singleton(cx),
 744            )
 745        });
 746
 747        if has_conflict && can_save {
 748            let mut answer = pane.update(cx, |pane, cx| {
 749                pane.activate_item(item_ix, true, true, false, cx);
 750                cx.prompt(
 751                    PromptLevel::Warning,
 752                    CONFLICT_MESSAGE,
 753                    &["Overwrite", "Discard", "Cancel"],
 754                )
 755            });
 756            match answer.next().await {
 757                Some(0) => cx.update(|cx| item.save(project, cx)).await?,
 758                Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
 759                _ => return Ok(false),
 760            }
 761        } else if is_dirty && (can_save || is_singleton) {
 762            let will_autosave = cx.read(|cx| {
 763                matches!(
 764                    cx.global::<Settings>().autosave,
 765                    Autosave::OnFocusChange | Autosave::OnWindowChange
 766                ) && Self::can_autosave_item(&*item, cx)
 767            });
 768            let should_save = if should_prompt_for_save && !will_autosave {
 769                let mut answer = pane.update(cx, |pane, cx| {
 770                    pane.activate_item(item_ix, true, true, false, cx);
 771                    cx.prompt(
 772                        PromptLevel::Warning,
 773                        DIRTY_MESSAGE,
 774                        &["Save", "Don't Save", "Cancel"],
 775                    )
 776                });
 777                match answer.next().await {
 778                    Some(0) => true,
 779                    Some(1) => false,
 780                    _ => return Ok(false),
 781                }
 782            } else {
 783                true
 784            };
 785
 786            if should_save {
 787                if can_save {
 788                    cx.update(|cx| item.save(project, cx)).await?;
 789                } else if is_singleton {
 790                    let start_abs_path = project
 791                        .read_with(cx, |project, cx| {
 792                            let worktree = project.visible_worktrees(cx).next()?;
 793                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 794                        })
 795                        .unwrap_or_else(|| Path::new("").into());
 796
 797                    let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
 798                    if let Some(abs_path) = abs_path.next().await.flatten() {
 799                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
 800                    } else {
 801                        return Ok(false);
 802                    }
 803                }
 804            }
 805        }
 806        Ok(true)
 807    }
 808
 809    fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
 810        let is_deleted = item.project_entry_ids(cx).is_empty();
 811        item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
 812    }
 813
 814    pub fn autosave_item(
 815        item: &dyn ItemHandle,
 816        project: ModelHandle<Project>,
 817        cx: &mut MutableAppContext,
 818    ) -> Task<Result<()>> {
 819        if Self::can_autosave_item(item, cx) {
 820            item.save(project, cx)
 821        } else {
 822            Task::ready(Ok(()))
 823        }
 824    }
 825
 826    pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
 827        if let Some(active_item) = self.active_item() {
 828            cx.focus(active_item);
 829        }
 830    }
 831
 832    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
 833        cx.emit(Event::Split(direction));
 834    }
 835
 836    fn deploy_split_menu(&mut self, action: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
 837        self.context_menu.update(cx, |menu, cx| {
 838            menu.show(
 839                action.position,
 840                vec![
 841                    ContextMenuItem::item("Split Right", SplitRight),
 842                    ContextMenuItem::item("Split Left", SplitLeft),
 843                    ContextMenuItem::item("Split Up", SplitUp),
 844                    ContextMenuItem::item("Split Down", SplitDown),
 845                ],
 846                cx,
 847            );
 848        });
 849    }
 850
 851    fn deploy_new_menu(&mut self, action: &DeployNewMenu, cx: &mut ViewContext<Self>) {
 852        self.context_menu.update(cx, |menu, cx| {
 853            menu.show(
 854                action.position,
 855                vec![
 856                    ContextMenuItem::item("New File", NewFile),
 857                    ContextMenuItem::item("New Terminal", NewTerminal),
 858                    ContextMenuItem::item("New Search", NewSearch),
 859                ],
 860                cx,
 861            );
 862        });
 863    }
 864
 865    pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
 866        &self.toolbar
 867    }
 868
 869    fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
 870        let active_item = self
 871            .items
 872            .get(self.active_item_index)
 873            .map(|item| item.as_ref());
 874        self.toolbar.update(cx, |toolbar, cx| {
 875            toolbar.set_active_pane_item(active_item, cx);
 876        });
 877    }
 878
 879    fn render_tabs(&mut self, cx: &mut RenderContext<Self>) -> impl Element {
 880        let theme = cx.global::<Settings>().theme.clone();
 881
 882        enum Tabs {}
 883        enum Tab {}
 884        let pane = cx.handle();
 885        MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
 886            let autoscroll = if mem::take(&mut self.autoscroll) {
 887                Some(self.active_item_index)
 888            } else {
 889                None
 890            };
 891
 892            let is_pane_active = self.is_active;
 893
 894            let tab_styles = match is_pane_active {
 895                true => theme.workspace.tab_bar.active_pane.clone(),
 896                false => theme.workspace.tab_bar.inactive_pane.clone(),
 897            };
 898            let filler_style = tab_styles.inactive_tab.clone();
 899
 900            let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
 901            for (ix, (item, detail)) in self.items.iter().zip(self.tab_details(cx)).enumerate() {
 902                let item_id = item.id();
 903                let detail = if detail == 0 { None } else { Some(detail) };
 904                let is_tab_active = ix == self.active_item_index;
 905
 906                let close_tab_callback = {
 907                    let pane = pane.clone();
 908                    move |_, cx: &mut EventContext| {
 909                        cx.dispatch_action(CloseItem {
 910                            item_id,
 911                            pane: pane.clone(),
 912                        })
 913                    }
 914                };
 915
 916                row.add_child({
 917                    let mut tab_style = match is_tab_active {
 918                        true => tab_styles.active_tab.clone(),
 919                        false => tab_styles.inactive_tab.clone(),
 920                    };
 921
 922                    let title = item.tab_content(detail, &tab_style, cx);
 923
 924                    if ix == 0 {
 925                        tab_style.container.border.left = false;
 926                    }
 927
 928                    MouseEventHandler::new::<Tab, _, _>(ix, cx, |_, cx| {
 929                        Container::new(
 930                            Flex::row()
 931                                .with_child(
 932                                    Align::new({
 933                                        let diameter = 7.0;
 934                                        let icon_color = if item.has_conflict(cx) {
 935                                            Some(tab_style.icon_conflict)
 936                                        } else if item.is_dirty(cx) {
 937                                            Some(tab_style.icon_dirty)
 938                                        } else {
 939                                            None
 940                                        };
 941
 942                                        ConstrainedBox::new(
 943                                            Canvas::new(move |bounds, _, cx| {
 944                                                if let Some(color) = icon_color {
 945                                                    let square = RectF::new(
 946                                                        bounds.origin(),
 947                                                        vec2f(diameter, diameter),
 948                                                    );
 949                                                    cx.scene.push_quad(Quad {
 950                                                        bounds: square,
 951                                                        background: Some(color),
 952                                                        border: Default::default(),
 953                                                        corner_radius: diameter / 2.,
 954                                                    });
 955                                                }
 956                                            })
 957                                            .boxed(),
 958                                        )
 959                                        .with_width(diameter)
 960                                        .with_height(diameter)
 961                                        .boxed()
 962                                    })
 963                                    .boxed(),
 964                                )
 965                                .with_child(
 966                                    Container::new(Align::new(title).boxed())
 967                                        .with_style(ContainerStyle {
 968                                            margin: Margin {
 969                                                left: tab_style.spacing,
 970                                                right: tab_style.spacing,
 971                                                ..Default::default()
 972                                            },
 973                                            ..Default::default()
 974                                        })
 975                                        .boxed(),
 976                                )
 977                                .with_child(
 978                                    Align::new(
 979                                        ConstrainedBox::new(if mouse_state.hovered {
 980                                            enum TabCloseButton {}
 981                                            let icon = Svg::new("icons/x_mark_thin_8.svg");
 982                                            MouseEventHandler::new::<TabCloseButton, _, _>(
 983                                                item_id,
 984                                                cx,
 985                                                |mouse_state, _| {
 986                                                    if mouse_state.hovered {
 987                                                        icon.with_color(tab_style.icon_close_active)
 988                                                            .boxed()
 989                                                    } else {
 990                                                        icon.with_color(tab_style.icon_close)
 991                                                            .boxed()
 992                                                    }
 993                                                },
 994                                            )
 995                                            .with_padding(Padding::uniform(4.))
 996                                            .with_cursor_style(CursorStyle::PointingHand)
 997                                            .on_click(MouseButton::Left, close_tab_callback.clone())
 998                                            .on_click(
 999                                                MouseButton::Middle,
1000                                                close_tab_callback.clone(),
1001                                            )
1002                                            .named("close-tab-icon")
1003                                        } else {
1004                                            Empty::new().boxed()
1005                                        })
1006                                        .with_width(tab_style.icon_width)
1007                                        .boxed(),
1008                                    )
1009                                    .boxed(),
1010                                )
1011                                .boxed(),
1012                        )
1013                        .with_style(tab_style.container)
1014                        .boxed()
1015                    })
1016                    .with_cursor_style(if is_tab_active && is_pane_active {
1017                        CursorStyle::Arrow
1018                    } else {
1019                        CursorStyle::PointingHand
1020                    })
1021                    .on_down(MouseButton::Left, move |_, cx| {
1022                        cx.dispatch_action(ActivateItem(ix));
1023                    })
1024                    .on_click(MouseButton::Middle, close_tab_callback)
1025                    .boxed()
1026                })
1027            }
1028
1029            row.add_child(
1030                Empty::new()
1031                    .contained()
1032                    .with_style(filler_style.container)
1033                    .with_border(filler_style.container.border)
1034                    .flex(0., true)
1035                    .named("filler"),
1036            );
1037
1038            row.boxed()
1039        })
1040    }
1041
1042    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1043        let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1044
1045        let mut tab_descriptions = HashMap::default();
1046        let mut done = false;
1047        while !done {
1048            done = true;
1049
1050            // Store item indices by their tab description.
1051            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1052                if let Some(description) = item.tab_description(*detail, cx) {
1053                    if *detail == 0
1054                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1055                    {
1056                        tab_descriptions
1057                            .entry(description)
1058                            .or_insert(Vec::new())
1059                            .push(ix);
1060                    }
1061                }
1062            }
1063
1064            // If two or more items have the same tab description, increase their level
1065            // of detail and try again.
1066            for (_, item_ixs) in tab_descriptions.drain() {
1067                if item_ixs.len() > 1 {
1068                    done = false;
1069                    for ix in item_ixs {
1070                        tab_details[ix] += 1;
1071                    }
1072                }
1073            }
1074        }
1075
1076        tab_details
1077    }
1078}
1079
1080impl Entity for Pane {
1081    type Event = Event;
1082}
1083
1084impl View for Pane {
1085    fn ui_name() -> &'static str {
1086        "Pane"
1087    }
1088
1089    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1090        enum SplitIcon {}
1091
1092        let this = cx.handle();
1093
1094        Stack::new()
1095            .with_child(
1096                EventHandler::new(if let Some(active_item) = self.active_item() {
1097                    Flex::column()
1098                        .with_child({
1099                            let mut tab_row = Flex::row()
1100                                .with_child(self.render_tabs(cx).flex(1., true).named("tabs"));
1101
1102                            if self.is_active {
1103                                tab_row.add_children([
1104                                    MouseEventHandler::new::<SplitIcon, _, _>(
1105                                        0,
1106                                        cx,
1107                                        |mouse_state, cx| {
1108                                            let theme =
1109                                                &cx.global::<Settings>().theme.workspace.tab_bar;
1110                                            let style =
1111                                                theme.pane_button.style_for(mouse_state, false);
1112                                            Svg::new("icons/plus_12.svg")
1113                                                .with_color(style.color)
1114                                                .constrained()
1115                                                .with_width(style.icon_width)
1116                                                .aligned()
1117                                                .contained()
1118                                                .with_style(style.container)
1119                                                .constrained()
1120                                                .with_width(style.button_width)
1121                                                .with_height(style.button_width)
1122                                                .aligned()
1123                                                .boxed()
1124                                        },
1125                                    )
1126                                    .with_cursor_style(CursorStyle::PointingHand)
1127                                    .on_down(
1128                                        MouseButton::Left,
1129                                        |MouseButtonEvent { position, .. }, cx| {
1130                                            cx.dispatch_action(DeployNewMenu { position });
1131                                        },
1132                                    )
1133                                    .boxed(),
1134                                    MouseEventHandler::new::<SplitIcon, _, _>(
1135                                        1,
1136                                        cx,
1137                                        |mouse_state, cx| {
1138                                            let theme =
1139                                                &cx.global::<Settings>().theme.workspace.tab_bar;
1140                                            let style =
1141                                                theme.pane_button.style_for(mouse_state, false);
1142                                            Svg::new("icons/split_12.svg")
1143                                                .with_color(style.color)
1144                                                .constrained()
1145                                                .with_width(style.icon_width)
1146                                                .aligned()
1147                                                .contained()
1148                                                .with_style(style.container)
1149                                                .constrained()
1150                                                .with_width(style.button_width)
1151                                                .with_height(style.button_width)
1152                                                .aligned()
1153                                                .boxed()
1154                                        },
1155                                    )
1156                                    .with_cursor_style(CursorStyle::PointingHand)
1157                                    .on_down(
1158                                        MouseButton::Left,
1159                                        |MouseButtonEvent { position, .. }, cx| {
1160                                            cx.dispatch_action(DeploySplitMenu { position });
1161                                        },
1162                                    )
1163                                    .boxed(),
1164                                ])
1165                            }
1166
1167                            tab_row
1168                                .constrained()
1169                                .with_height(cx.global::<Settings>().theme.workspace.tab_bar.height)
1170                                .boxed()
1171                        })
1172                        .with_child(ChildView::new(&self.toolbar).boxed())
1173                        .with_child(ChildView::new(active_item).flex(1., true).boxed())
1174                        .boxed()
1175                } else {
1176                    enum EmptyPane {}
1177                    let theme = cx.global::<Settings>().theme.clone();
1178
1179                    MouseEventHandler::new::<EmptyPane, _, _>(0, cx, |_, _| {
1180                        Empty::new()
1181                            .contained()
1182                            .with_background_color(theme.workspace.background)
1183                            .boxed()
1184                    })
1185                    .on_down(MouseButton::Left, |_, cx| {
1186                        cx.focus_parent_view();
1187                    })
1188                    .boxed()
1189                })
1190                .on_navigate_mouse_down(move |direction, cx| {
1191                    let this = this.clone();
1192                    match direction {
1193                        NavigationDirection::Back => {
1194                            cx.dispatch_action(GoBack { pane: Some(this) })
1195                        }
1196                        NavigationDirection::Forward => {
1197                            cx.dispatch_action(GoForward { pane: Some(this) })
1198                        }
1199                    }
1200
1201                    true
1202                })
1203                .boxed(),
1204            )
1205            .with_child(ChildView::new(&self.context_menu).boxed())
1206            .named("pane")
1207    }
1208
1209    fn on_focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1210        if cx.is_self_focused() {
1211            if let Some(last_focused_view) = self
1212                .last_focused_view
1213                .as_ref()
1214                .and_then(|handle| handle.upgrade(cx))
1215            {
1216                cx.focus(last_focused_view);
1217            } else {
1218                self.focus_active_item(cx);
1219            }
1220        } else {
1221            self.last_focused_view = Some(focused.downgrade());
1222        }
1223        cx.emit(Event::Focused);
1224    }
1225}
1226
1227impl ItemNavHistory {
1228    pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut MutableAppContext) {
1229        self.history.borrow_mut().push(data, self.item.clone(), cx);
1230    }
1231
1232    pub fn pop_backward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1233        self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1234    }
1235
1236    pub fn pop_forward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1237        self.history
1238            .borrow_mut()
1239            .pop(NavigationMode::GoingForward, cx)
1240    }
1241}
1242
1243impl NavHistory {
1244    fn set_mode(&mut self, mode: NavigationMode) {
1245        self.mode = mode;
1246    }
1247
1248    fn disable(&mut self) {
1249        self.mode = NavigationMode::Disabled;
1250    }
1251
1252    fn enable(&mut self) {
1253        self.mode = NavigationMode::Normal;
1254    }
1255
1256    fn pop(&mut self, mode: NavigationMode, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1257        let entry = match mode {
1258            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1259                return None
1260            }
1261            NavigationMode::GoingBack => &mut self.backward_stack,
1262            NavigationMode::GoingForward => &mut self.forward_stack,
1263            NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1264        }
1265        .pop_back();
1266        if entry.is_some() {
1267            self.did_update(cx);
1268        }
1269        entry
1270    }
1271
1272    fn push<D: 'static + Any>(
1273        &mut self,
1274        data: Option<D>,
1275        item: Rc<dyn WeakItemHandle>,
1276        cx: &mut MutableAppContext,
1277    ) {
1278        match self.mode {
1279            NavigationMode::Disabled => {}
1280            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1281                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1282                    self.backward_stack.pop_front();
1283                }
1284                self.backward_stack.push_back(NavigationEntry {
1285                    item,
1286                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1287                });
1288                self.forward_stack.clear();
1289            }
1290            NavigationMode::GoingBack => {
1291                if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1292                    self.forward_stack.pop_front();
1293                }
1294                self.forward_stack.push_back(NavigationEntry {
1295                    item,
1296                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1297                });
1298            }
1299            NavigationMode::GoingForward => {
1300                if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1301                    self.backward_stack.pop_front();
1302                }
1303                self.backward_stack.push_back(NavigationEntry {
1304                    item,
1305                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1306                });
1307            }
1308            NavigationMode::ClosingItem => {
1309                if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1310                    self.closed_stack.pop_front();
1311                }
1312                self.closed_stack.push_back(NavigationEntry {
1313                    item,
1314                    data: data.map(|data| Box::new(data) as Box<dyn Any>),
1315                });
1316            }
1317        }
1318        self.did_update(cx);
1319    }
1320
1321    fn did_update(&self, cx: &mut MutableAppContext) {
1322        if let Some(pane) = self.pane.upgrade(cx) {
1323            cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1324        }
1325    }
1326}