pane.rs

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