pane.rs

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