pane.rs

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