pane.rs

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