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