workspace.rs

   1pub mod pane;
   2pub mod pane_group;
   3pub mod sidebar;
   4mod status_bar;
   5mod toolbar;
   6mod waiting_room;
   7
   8use anyhow::{anyhow, Context, Result};
   9use client::{
  10    proto, Authenticate, Client, Contact, PeerId, Subscription, TypedEnvelope, User, UserStore,
  11};
  12use clock::ReplicaId;
  13use collections::{hash_map, HashMap, HashSet};
  14use futures::{channel::oneshot, FutureExt};
  15use gpui::{
  16    actions,
  17    color::Color,
  18    elements::*,
  19    geometry::{rect::RectF, vector::vec2f, PathBuilder},
  20    impl_actions, impl_internal_actions,
  21    json::{self, ToJson},
  22    platform::{CursorStyle, WindowOptions},
  23    AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, Entity, ImageData,
  24    ModelContext, ModelHandle, MouseButton, MutableAppContext, PathPromptOptions, PromptLevel,
  25    RenderContext, Task, View, ViewContext, ViewHandle, WeakViewHandle,
  26};
  27use language::LanguageRegistry;
  28use log::error;
  29pub use pane::*;
  30pub use pane_group::*;
  31use postage::prelude::Stream;
  32use project::{fs, Fs, Project, ProjectEntryId, ProjectPath, ProjectStore, Worktree, WorktreeId};
  33use serde::Deserialize;
  34use settings::{Autosave, Settings};
  35use sidebar::{Side, Sidebar, SidebarButtons, ToggleSidebarItem};
  36use smallvec::SmallVec;
  37use status_bar::StatusBar;
  38pub use status_bar::StatusItemView;
  39use std::{
  40    any::{Any, TypeId},
  41    borrow::Cow,
  42    cell::RefCell,
  43    fmt,
  44    future::Future,
  45    mem,
  46    path::{Path, PathBuf},
  47    rc::Rc,
  48    sync::{
  49        atomic::{AtomicBool, Ordering::SeqCst},
  50        Arc,
  51    },
  52    time::Duration,
  53};
  54use theme::{Theme, ThemeRegistry};
  55pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
  56use util::ResultExt;
  57use waiting_room::WaitingRoom;
  58
  59type ProjectItemBuilders = HashMap<
  60    TypeId,
  61    fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
  62>;
  63
  64type FollowableItemBuilder = fn(
  65    ViewHandle<Pane>,
  66    ModelHandle<Project>,
  67    &mut Option<proto::view::Variant>,
  68    &mut MutableAppContext,
  69) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
  70type FollowableItemBuilders = HashMap<
  71    TypeId,
  72    (
  73        FollowableItemBuilder,
  74        fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
  75    ),
  76>;
  77
  78#[derive(Clone, PartialEq)]
  79pub struct RemoveWorktreeFromProject(pub WorktreeId);
  80
  81actions!(
  82    workspace,
  83    [
  84        Open,
  85        NewFile,
  86        NewWindow,
  87        CloseWindow,
  88        AddFolderToProject,
  89        Unfollow,
  90        Save,
  91        SaveAs,
  92        SaveAll,
  93        ActivatePreviousPane,
  94        ActivateNextPane,
  95        FollowNextCollaborator,
  96        ToggleLeftSidebar,
  97        ToggleRightSidebar,
  98    ]
  99);
 100
 101#[derive(Clone, PartialEq)]
 102pub struct OpenPaths {
 103    pub paths: Vec<PathBuf>,
 104}
 105
 106#[derive(Clone, Deserialize, PartialEq)]
 107pub struct ToggleProjectOnline {
 108    #[serde(skip_deserializing)]
 109    pub project: Option<ModelHandle<Project>>,
 110}
 111
 112#[derive(Clone, Deserialize, PartialEq)]
 113pub struct ActivatePane(pub usize);
 114
 115#[derive(Clone, PartialEq)]
 116pub struct ToggleFollow(pub PeerId);
 117
 118#[derive(Clone, PartialEq)]
 119pub struct JoinProject {
 120    pub contact: Arc<Contact>,
 121    pub project_index: usize,
 122}
 123
 124impl_internal_actions!(
 125    workspace,
 126    [
 127        OpenPaths,
 128        ToggleFollow,
 129        JoinProject,
 130        RemoveWorktreeFromProject
 131    ]
 132);
 133impl_actions!(workspace, [ToggleProjectOnline, ActivatePane]);
 134
 135pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
 136    pane::init(cx);
 137
 138    cx.add_global_action(open);
 139    cx.add_global_action({
 140        let app_state = Arc::downgrade(&app_state);
 141        move |action: &OpenPaths, cx: &mut MutableAppContext| {
 142            if let Some(app_state) = app_state.upgrade() {
 143                open_paths(&action.paths, &app_state, cx).detach();
 144            }
 145        }
 146    });
 147    cx.add_global_action({
 148        let app_state = Arc::downgrade(&app_state);
 149        move |_: &NewFile, cx: &mut MutableAppContext| {
 150            if let Some(app_state) = app_state.upgrade() {
 151                open_new(&app_state, cx)
 152            }
 153        }
 154    });
 155    cx.add_global_action({
 156        let app_state = Arc::downgrade(&app_state);
 157        move |_: &NewWindow, cx: &mut MutableAppContext| {
 158            if let Some(app_state) = app_state.upgrade() {
 159                open_new(&app_state, cx)
 160            }
 161        }
 162    });
 163    cx.add_global_action({
 164        let app_state = Arc::downgrade(&app_state);
 165        move |action: &JoinProject, cx: &mut MutableAppContext| {
 166            if let Some(app_state) = app_state.upgrade() {
 167                join_project(action.contact.clone(), action.project_index, &app_state, cx);
 168            }
 169        }
 170    });
 171
 172    cx.add_async_action(Workspace::toggle_follow);
 173    cx.add_async_action(Workspace::follow_next_collaborator);
 174    cx.add_async_action(Workspace::close);
 175    cx.add_async_action(Workspace::save_all);
 176    cx.add_action(Workspace::add_folder_to_project);
 177    cx.add_action(Workspace::remove_folder_from_project);
 178    cx.add_action(Workspace::toggle_project_online);
 179    cx.add_action(
 180        |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
 181            let pane = workspace.active_pane().clone();
 182            workspace.unfollow(&pane, cx);
 183        },
 184    );
 185    cx.add_action(
 186        |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
 187            workspace.save_active_item(false, cx).detach_and_log_err(cx);
 188        },
 189    );
 190    cx.add_action(
 191        |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
 192            workspace.save_active_item(true, cx).detach_and_log_err(cx);
 193        },
 194    );
 195    cx.add_action(Workspace::toggle_sidebar_item);
 196    cx.add_action(Workspace::focus_center);
 197    cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
 198        workspace.activate_previous_pane(cx)
 199    });
 200    cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
 201        workspace.activate_next_pane(cx)
 202    });
 203    cx.add_action(|workspace: &mut Workspace, _: &ToggleLeftSidebar, cx| {
 204        workspace.toggle_sidebar(Side::Left, cx);
 205    });
 206    cx.add_action(|workspace: &mut Workspace, _: &ToggleRightSidebar, cx| {
 207        workspace.toggle_sidebar(Side::Right, cx);
 208    });
 209    cx.add_action(Workspace::activate_pane_at_index);
 210
 211    let client = &app_state.client;
 212    client.add_view_request_handler(Workspace::handle_follow);
 213    client.add_view_message_handler(Workspace::handle_unfollow);
 214    client.add_view_message_handler(Workspace::handle_update_followers);
 215}
 216
 217pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
 218    cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
 219        builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
 220            let item = model.downcast::<I::Item>().unwrap();
 221            Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
 222        });
 223    });
 224}
 225
 226pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
 227    cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
 228        builders.insert(
 229            TypeId::of::<I>(),
 230            (
 231                |pane, project, state, cx| {
 232                    I::from_state_proto(pane, project, state, cx).map(|task| {
 233                        cx.foreground()
 234                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
 235                    })
 236                },
 237                |this| Box::new(this.downcast::<I>().unwrap()),
 238            ),
 239        );
 240    });
 241}
 242
 243pub struct AppState {
 244    pub languages: Arc<LanguageRegistry>,
 245    pub themes: Arc<ThemeRegistry>,
 246    pub client: Arc<client::Client>,
 247    pub user_store: ModelHandle<client::UserStore>,
 248    pub project_store: ModelHandle<ProjectStore>,
 249    pub fs: Arc<dyn fs::Fs>,
 250    pub build_window_options: fn() -> WindowOptions<'static>,
 251    pub initialize_workspace: fn(&mut Workspace, &Arc<AppState>, &mut ViewContext<Workspace>),
 252}
 253
 254pub trait Item: View {
 255    fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
 256    fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
 257        false
 258    }
 259    fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
 260        None
 261    }
 262    fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
 263        -> ElementBox;
 264    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 265    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 266    fn is_singleton(&self, cx: &AppContext) -> bool;
 267    fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
 268    fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
 269    where
 270        Self: Sized,
 271    {
 272        None
 273    }
 274    fn is_dirty(&self, _: &AppContext) -> bool {
 275        false
 276    }
 277    fn has_conflict(&self, _: &AppContext) -> bool {
 278        false
 279    }
 280    fn can_save(&self, cx: &AppContext) -> bool;
 281    fn save(
 282        &mut self,
 283        project: ModelHandle<Project>,
 284        cx: &mut ViewContext<Self>,
 285    ) -> Task<Result<()>>;
 286    fn save_as(
 287        &mut self,
 288        project: ModelHandle<Project>,
 289        abs_path: PathBuf,
 290        cx: &mut ViewContext<Self>,
 291    ) -> Task<Result<()>>;
 292    fn reload(
 293        &mut self,
 294        project: ModelHandle<Project>,
 295        cx: &mut ViewContext<Self>,
 296    ) -> Task<Result<()>>;
 297    fn should_activate_item_on_event(_: &Self::Event) -> bool {
 298        false
 299    }
 300    fn should_close_item_on_event(_: &Self::Event) -> bool {
 301        false
 302    }
 303    fn should_update_tab_on_event(_: &Self::Event) -> bool {
 304        false
 305    }
 306    fn is_edit_event(_: &Self::Event) -> bool {
 307        false
 308    }
 309    fn act_as_type(
 310        &self,
 311        type_id: TypeId,
 312        self_handle: &ViewHandle<Self>,
 313        _: &AppContext,
 314    ) -> Option<AnyViewHandle> {
 315        if TypeId::of::<Self>() == type_id {
 316            Some(self_handle.into())
 317        } else {
 318            None
 319        }
 320    }
 321}
 322
 323pub trait ProjectItem: Item {
 324    type Item: project::Item;
 325
 326    fn for_project_item(
 327        project: ModelHandle<Project>,
 328        item: ModelHandle<Self::Item>,
 329        cx: &mut ViewContext<Self>,
 330    ) -> Self;
 331}
 332
 333pub trait FollowableItem: Item {
 334    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 335    fn from_state_proto(
 336        pane: ViewHandle<Pane>,
 337        project: ModelHandle<Project>,
 338        state: &mut Option<proto::view::Variant>,
 339        cx: &mut MutableAppContext,
 340    ) -> Option<Task<Result<ViewHandle<Self>>>>;
 341    fn add_event_to_update_proto(
 342        &self,
 343        event: &Self::Event,
 344        update: &mut Option<proto::update_view::Variant>,
 345        cx: &AppContext,
 346    ) -> bool;
 347    fn apply_update_proto(
 348        &mut self,
 349        message: proto::update_view::Variant,
 350        cx: &mut ViewContext<Self>,
 351    ) -> Result<()>;
 352
 353    fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
 354    fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
 355}
 356
 357pub trait FollowableItemHandle: ItemHandle {
 358    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
 359    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 360    fn add_event_to_update_proto(
 361        &self,
 362        event: &dyn Any,
 363        update: &mut Option<proto::update_view::Variant>,
 364        cx: &AppContext,
 365    ) -> bool;
 366    fn apply_update_proto(
 367        &self,
 368        message: proto::update_view::Variant,
 369        cx: &mut MutableAppContext,
 370    ) -> Result<()>;
 371    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
 372}
 373
 374impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
 375    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
 376        self.update(cx, |this, cx| {
 377            this.set_leader_replica_id(leader_replica_id, cx)
 378        })
 379    }
 380
 381    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
 382        self.read(cx).to_state_proto(cx)
 383    }
 384
 385    fn add_event_to_update_proto(
 386        &self,
 387        event: &dyn Any,
 388        update: &mut Option<proto::update_view::Variant>,
 389        cx: &AppContext,
 390    ) -> bool {
 391        if let Some(event) = event.downcast_ref() {
 392            self.read(cx).add_event_to_update_proto(event, update, cx)
 393        } else {
 394            false
 395        }
 396    }
 397
 398    fn apply_update_proto(
 399        &self,
 400        message: proto::update_view::Variant,
 401        cx: &mut MutableAppContext,
 402    ) -> Result<()> {
 403        self.update(cx, |this, cx| this.apply_update_proto(message, cx))
 404    }
 405
 406    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
 407        if let Some(event) = event.downcast_ref() {
 408            T::should_unfollow_on_event(event, cx)
 409        } else {
 410            false
 411        }
 412    }
 413}
 414
 415pub trait ItemHandle: 'static + fmt::Debug {
 416    fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;
 417    fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
 418        -> ElementBox;
 419    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 420    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 421    fn is_singleton(&self, cx: &AppContext) -> bool;
 422    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 423    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
 424    fn added_to_pane(
 425        &self,
 426        workspace: &mut Workspace,
 427        pane: ViewHandle<Pane>,
 428        cx: &mut ViewContext<Workspace>,
 429    );
 430    fn deactivated(&self, cx: &mut MutableAppContext);
 431    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
 432    fn id(&self) -> usize;
 433    fn to_any(&self) -> AnyViewHandle;
 434    fn is_dirty(&self, cx: &AppContext) -> bool;
 435    fn has_conflict(&self, cx: &AppContext) -> bool;
 436    fn can_save(&self, cx: &AppContext) -> bool;
 437    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
 438    fn save_as(
 439        &self,
 440        project: ModelHandle<Project>,
 441        abs_path: PathBuf,
 442        cx: &mut MutableAppContext,
 443    ) -> Task<Result<()>>;
 444    fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)
 445        -> Task<Result<()>>;
 446    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
 447    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
 448    fn on_release(
 449        &self,
 450        cx: &mut MutableAppContext,
 451        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
 452    ) -> gpui::Subscription;
 453}
 454
 455pub trait WeakItemHandle {
 456    fn id(&self) -> usize;
 457    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
 458}
 459
 460impl dyn ItemHandle {
 461    pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
 462        self.to_any().downcast()
 463    }
 464
 465    pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
 466        self.act_as_type(TypeId::of::<T>(), cx)
 467            .and_then(|t| t.downcast())
 468    }
 469}
 470
 471impl<T: Item> ItemHandle for ViewHandle<T> {
 472    fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
 473        self.read(cx).tab_description(detail, cx)
 474    }
 475
 476    fn tab_content(
 477        &self,
 478        detail: Option<usize>,
 479        style: &theme::Tab,
 480        cx: &AppContext,
 481    ) -> ElementBox {
 482        self.read(cx).tab_content(detail, style, cx)
 483    }
 484
 485    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 486        self.read(cx).project_path(cx)
 487    }
 488
 489    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
 490        self.read(cx).project_entry_ids(cx)
 491    }
 492
 493    fn is_singleton(&self, cx: &AppContext) -> bool {
 494        self.read(cx).is_singleton(cx)
 495    }
 496
 497    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 498        Box::new(self.clone())
 499    }
 500
 501    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
 502        self.update(cx, |item, cx| {
 503            cx.add_option_view(|cx| item.clone_on_split(cx))
 504        })
 505        .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 506    }
 507
 508    fn added_to_pane(
 509        &self,
 510        workspace: &mut Workspace,
 511        pane: ViewHandle<Pane>,
 512        cx: &mut ViewContext<Workspace>,
 513    ) {
 514        let history = pane.read(cx).nav_history_for_item(self);
 515        self.update(cx, |this, cx| this.set_nav_history(history, cx));
 516
 517        if let Some(followed_item) = self.to_followable_item_handle(cx) {
 518            if let Some(message) = followed_item.to_state_proto(cx) {
 519                workspace.update_followers(
 520                    proto::update_followers::Variant::CreateView(proto::View {
 521                        id: followed_item.id() as u64,
 522                        variant: Some(message),
 523                        leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
 524                    }),
 525                    cx,
 526                );
 527            }
 528        }
 529
 530        let mut pending_autosave = None;
 531        let mut cancel_pending_autosave = oneshot::channel::<()>().0;
 532        let pending_update = Rc::new(RefCell::new(None));
 533        let pending_update_scheduled = Rc::new(AtomicBool::new(false));
 534        let pane = pane.downgrade();
 535        cx.subscribe(self, move |workspace, item, event, cx| {
 536            let pane = if let Some(pane) = pane.upgrade(cx) {
 537                pane
 538            } else {
 539                log::error!("unexpected item event after pane was dropped");
 540                return;
 541            };
 542
 543            if let Some(item) = item.to_followable_item_handle(cx) {
 544                let leader_id = workspace.leader_for_pane(&pane);
 545
 546                if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
 547                    workspace.unfollow(&pane, cx);
 548                }
 549
 550                if item.add_event_to_update_proto(event, &mut *pending_update.borrow_mut(), cx)
 551                    && !pending_update_scheduled.load(SeqCst)
 552                {
 553                    pending_update_scheduled.store(true, SeqCst);
 554                    cx.after_window_update({
 555                        let pending_update = pending_update.clone();
 556                        let pending_update_scheduled = pending_update_scheduled.clone();
 557                        move |this, cx| {
 558                            pending_update_scheduled.store(false, SeqCst);
 559                            this.update_followers(
 560                                proto::update_followers::Variant::UpdateView(proto::UpdateView {
 561                                    id: item.id() as u64,
 562                                    variant: pending_update.borrow_mut().take(),
 563                                    leader_id: leader_id.map(|id| id.0),
 564                                }),
 565                                cx,
 566                            );
 567                        }
 568                    });
 569                }
 570            }
 571
 572            if T::should_close_item_on_event(event) {
 573                Pane::close_item(workspace, pane, item.id(), cx).detach_and_log_err(cx);
 574                return;
 575            }
 576
 577            if T::should_activate_item_on_event(event) {
 578                pane.update(cx, |pane, cx| {
 579                    if let Some(ix) = pane.index_for_item(&item) {
 580                        pane.activate_item(ix, true, true, false, cx);
 581                        pane.activate(cx);
 582                    }
 583                });
 584            }
 585
 586            if T::should_update_tab_on_event(event) {
 587                pane.update(cx, |_, cx| {
 588                    cx.emit(pane::Event::ChangeItemTitle);
 589                    cx.notify();
 590                });
 591            }
 592
 593            if T::is_edit_event(event) {
 594                if let Autosave::AfterDelay { milliseconds } = cx.global::<Settings>().autosave {
 595                    let prev_autosave = pending_autosave.take().unwrap_or(Task::ready(Some(())));
 596                    let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
 597                    let prev_cancel_tx = mem::replace(&mut cancel_pending_autosave, cancel_tx);
 598                    let project = workspace.project.downgrade();
 599                    let _ = prev_cancel_tx.send(());
 600                    pending_autosave = Some(cx.spawn_weak(|_, mut cx| async move {
 601                        let mut timer = cx
 602                            .background()
 603                            .timer(Duration::from_millis(milliseconds))
 604                            .fuse();
 605                        prev_autosave.await;
 606                        futures::select_biased! {
 607                            _ = cancel_rx => return None,
 608                            _ = timer => {}
 609                        }
 610
 611                        let project = project.upgrade(&cx)?;
 612                        cx.update(|cx| Pane::autosave_item(&item, project, cx))
 613                            .await
 614                            .log_err();
 615                        None
 616                    }));
 617                }
 618            }
 619        })
 620        .detach();
 621
 622        cx.observe_focus(self, move |workspace, item, focused, cx| {
 623            if !focused && cx.global::<Settings>().autosave == Autosave::OnFocusChange {
 624                Pane::autosave_item(&item, workspace.project.clone(), cx).detach_and_log_err(cx);
 625            }
 626        })
 627        .detach();
 628    }
 629
 630    fn deactivated(&self, cx: &mut MutableAppContext) {
 631        self.update(cx, |this, cx| this.deactivated(cx));
 632    }
 633
 634    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {
 635        self.update(cx, |this, cx| this.navigate(data, cx))
 636    }
 637
 638    fn id(&self) -> usize {
 639        self.id()
 640    }
 641
 642    fn to_any(&self) -> AnyViewHandle {
 643        self.into()
 644    }
 645
 646    fn is_dirty(&self, cx: &AppContext) -> bool {
 647        self.read(cx).is_dirty(cx)
 648    }
 649
 650    fn has_conflict(&self, cx: &AppContext) -> bool {
 651        self.read(cx).has_conflict(cx)
 652    }
 653
 654    fn can_save(&self, cx: &AppContext) -> bool {
 655        self.read(cx).can_save(cx)
 656    }
 657
 658    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
 659        self.update(cx, |item, cx| item.save(project, cx))
 660    }
 661
 662    fn save_as(
 663        &self,
 664        project: ModelHandle<Project>,
 665        abs_path: PathBuf,
 666        cx: &mut MutableAppContext,
 667    ) -> Task<anyhow::Result<()>> {
 668        self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
 669    }
 670
 671    fn reload(
 672        &self,
 673        project: ModelHandle<Project>,
 674        cx: &mut MutableAppContext,
 675    ) -> Task<Result<()>> {
 676        self.update(cx, |item, cx| item.reload(project, cx))
 677    }
 678
 679    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
 680        self.read(cx).act_as_type(type_id, self, cx)
 681    }
 682
 683    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 684        if cx.has_global::<FollowableItemBuilders>() {
 685            let builders = cx.global::<FollowableItemBuilders>();
 686            let item = self.to_any();
 687            Some(builders.get(&item.view_type())?.1(item))
 688        } else {
 689            None
 690        }
 691    }
 692
 693    fn on_release(
 694        &self,
 695        cx: &mut MutableAppContext,
 696        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
 697    ) -> gpui::Subscription {
 698        cx.observe_release(self, move |_, cx| callback(cx))
 699    }
 700}
 701
 702impl Into<AnyViewHandle> for Box<dyn ItemHandle> {
 703    fn into(self) -> AnyViewHandle {
 704        self.to_any()
 705    }
 706}
 707
 708impl Clone for Box<dyn ItemHandle> {
 709    fn clone(&self) -> Box<dyn ItemHandle> {
 710        self.boxed_clone()
 711    }
 712}
 713
 714impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
 715    fn id(&self) -> usize {
 716        self.id()
 717    }
 718
 719    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 720        self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
 721    }
 722}
 723
 724pub trait Notification: View {
 725    fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool;
 726}
 727
 728pub trait NotificationHandle {
 729    fn id(&self) -> usize;
 730    fn to_any(&self) -> AnyViewHandle;
 731}
 732
 733impl<T: Notification> NotificationHandle for ViewHandle<T> {
 734    fn id(&self) -> usize {
 735        self.id()
 736    }
 737
 738    fn to_any(&self) -> AnyViewHandle {
 739        self.into()
 740    }
 741}
 742
 743impl Into<AnyViewHandle> for &dyn NotificationHandle {
 744    fn into(self) -> AnyViewHandle {
 745        self.to_any()
 746    }
 747}
 748
 749impl AppState {
 750    #[cfg(any(test, feature = "test-support"))]
 751    pub fn test(cx: &mut MutableAppContext) -> Arc<Self> {
 752        let settings = Settings::test(cx);
 753        cx.set_global(settings);
 754
 755        let fs = project::FakeFs::new(cx.background().clone());
 756        let languages = Arc::new(LanguageRegistry::test());
 757        let http_client = client::test::FakeHttpClient::with_404_response();
 758        let client = Client::new(http_client.clone());
 759        let project_store = cx.add_model(|_| ProjectStore::new(project::Db::open_fake()));
 760        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 761        let themes = ThemeRegistry::new((), cx.font_cache().clone());
 762        Arc::new(Self {
 763            client,
 764            themes,
 765            fs,
 766            languages,
 767            user_store,
 768            project_store,
 769            initialize_workspace: |_, _, _| {},
 770            build_window_options: || Default::default(),
 771        })
 772    }
 773}
 774
 775pub enum Event {
 776    PaneAdded(ViewHandle<Pane>),
 777    ContactRequestedJoin(u64),
 778}
 779
 780pub struct Workspace {
 781    weak_self: WeakViewHandle<Self>,
 782    client: Arc<Client>,
 783    user_store: ModelHandle<client::UserStore>,
 784    remote_entity_subscription: Option<Subscription>,
 785    fs: Arc<dyn Fs>,
 786    modal: Option<AnyViewHandle>,
 787    center: PaneGroup,
 788    left_sidebar: ViewHandle<Sidebar>,
 789    right_sidebar: ViewHandle<Sidebar>,
 790    panes: Vec<ViewHandle<Pane>>,
 791    active_pane: ViewHandle<Pane>,
 792    status_bar: ViewHandle<StatusBar>,
 793    notifications: Vec<(TypeId, usize, Box<dyn NotificationHandle>)>,
 794    project: ModelHandle<Project>,
 795    leader_state: LeaderState,
 796    follower_states_by_leader: FollowerStatesByLeader,
 797    last_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,
 798    window_edited: bool,
 799    _observe_current_user: Task<()>,
 800}
 801
 802#[derive(Default)]
 803struct LeaderState {
 804    followers: HashSet<PeerId>,
 805}
 806
 807type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
 808
 809#[derive(Default)]
 810struct FollowerState {
 811    active_view_id: Option<u64>,
 812    items_by_leader_view_id: HashMap<u64, FollowerItem>,
 813}
 814
 815#[derive(Debug)]
 816enum FollowerItem {
 817    Loading(Vec<proto::update_view::Variant>),
 818    Loaded(Box<dyn FollowableItemHandle>),
 819}
 820
 821impl Workspace {
 822    pub fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
 823        cx.observe_window_activation(Self::on_window_activation_changed)
 824            .detach();
 825        cx.observe(&project, |_, _, cx| cx.notify()).detach();
 826        cx.subscribe(&project, move |this, _, event, cx| {
 827            match event {
 828                project::Event::RemoteIdChanged(remote_id) => {
 829                    this.project_remote_id_changed(*remote_id, cx);
 830                }
 831                project::Event::CollaboratorLeft(peer_id) => {
 832                    this.collaborator_left(*peer_id, cx);
 833                }
 834                project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded => {
 835                    this.update_window_title(cx);
 836                }
 837                project::Event::DisconnectedFromHost => {
 838                    this.update_window_edited(cx);
 839                    cx.blur();
 840                }
 841                _ => {}
 842            }
 843            cx.notify()
 844        })
 845        .detach();
 846
 847        let pane = cx.add_view(|cx| Pane::new(cx));
 848        let pane_id = pane.id();
 849        cx.subscribe(&pane, move |this, _, event, cx| {
 850            this.handle_pane_event(pane_id, event, cx)
 851        })
 852        .detach();
 853        cx.focus(&pane);
 854        cx.emit(Event::PaneAdded(pane.clone()));
 855
 856        let fs = project.read(cx).fs().clone();
 857        let user_store = project.read(cx).user_store();
 858        let client = project.read(cx).client();
 859        let mut current_user = user_store.read(cx).watch_current_user().clone();
 860        let mut connection_status = client.status().clone();
 861        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 862            current_user.recv().await;
 863            connection_status.recv().await;
 864            let mut stream =
 865                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 866
 867            while stream.recv().await.is_some() {
 868                cx.update(|cx| {
 869                    if let Some(this) = this.upgrade(cx) {
 870                        this.update(cx, |_, cx| cx.notify());
 871                    }
 872                })
 873            }
 874        });
 875
 876        let weak_self = cx.weak_handle();
 877
 878        cx.emit_global(WorkspaceCreated(weak_self.clone()));
 879
 880        let left_sidebar = cx.add_view(|_| Sidebar::new(Side::Left));
 881        let right_sidebar = cx.add_view(|_| Sidebar::new(Side::Right));
 882        let left_sidebar_buttons = cx.add_view(|cx| SidebarButtons::new(left_sidebar.clone(), cx));
 883        let right_sidebar_buttons =
 884            cx.add_view(|cx| SidebarButtons::new(right_sidebar.clone(), cx));
 885        let status_bar = cx.add_view(|cx| {
 886            let mut status_bar = StatusBar::new(&pane.clone(), cx);
 887            status_bar.add_left_item(left_sidebar_buttons, cx);
 888            status_bar.add_right_item(right_sidebar_buttons, cx);
 889            status_bar
 890        });
 891
 892        let mut this = Workspace {
 893            modal: None,
 894            weak_self,
 895            center: PaneGroup::new(pane.clone()),
 896            panes: vec![pane.clone()],
 897            active_pane: pane.clone(),
 898            status_bar,
 899            notifications: Default::default(),
 900            client,
 901            remote_entity_subscription: None,
 902            user_store,
 903            fs,
 904            left_sidebar,
 905            right_sidebar,
 906            project,
 907            leader_state: Default::default(),
 908            follower_states_by_leader: Default::default(),
 909            last_leaders_by_pane: Default::default(),
 910            window_edited: false,
 911            _observe_current_user,
 912        };
 913        this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
 914        cx.defer(|this, cx| this.update_window_title(cx));
 915
 916        this
 917    }
 918
 919    pub fn weak_handle(&self) -> WeakViewHandle<Self> {
 920        self.weak_self.clone()
 921    }
 922
 923    pub fn left_sidebar(&self) -> &ViewHandle<Sidebar> {
 924        &self.left_sidebar
 925    }
 926
 927    pub fn right_sidebar(&self) -> &ViewHandle<Sidebar> {
 928        &self.right_sidebar
 929    }
 930
 931    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
 932        &self.status_bar
 933    }
 934
 935    pub fn user_store(&self) -> &ModelHandle<UserStore> {
 936        &self.user_store
 937    }
 938
 939    pub fn project(&self) -> &ModelHandle<Project> {
 940        &self.project
 941    }
 942
 943    /// Call the given callback with a workspace whose project is local.
 944    ///
 945    /// If the given workspace has a local project, then it will be passed
 946    /// to the callback. Otherwise, a new empty window will be created.
 947    pub fn with_local_workspace<T, F>(
 948        &mut self,
 949        cx: &mut ViewContext<Self>,
 950        app_state: Arc<AppState>,
 951        mut callback: F,
 952    ) -> T
 953    where
 954        T: 'static,
 955        F: FnMut(&mut Workspace, &mut ViewContext<Workspace>) -> T,
 956    {
 957        if self.project.read(cx).is_local() {
 958            callback(self, cx)
 959        } else {
 960            let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
 961                let mut workspace = Workspace::new(
 962                    Project::local(
 963                        false,
 964                        app_state.client.clone(),
 965                        app_state.user_store.clone(),
 966                        app_state.project_store.clone(),
 967                        app_state.languages.clone(),
 968                        app_state.fs.clone(),
 969                        cx,
 970                    ),
 971                    cx,
 972                );
 973                (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
 974                workspace
 975            });
 976            workspace.update(cx, callback)
 977        }
 978    }
 979
 980    pub fn worktrees<'a>(
 981        &self,
 982        cx: &'a AppContext,
 983    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 984        self.project.read(cx).worktrees(cx)
 985    }
 986
 987    pub fn visible_worktrees<'a>(
 988        &self,
 989        cx: &'a AppContext,
 990    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 991        self.project.read(cx).visible_worktrees(cx)
 992    }
 993
 994    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
 995        let futures = self
 996            .worktrees(cx)
 997            .filter_map(|worktree| worktree.read(cx).as_local())
 998            .map(|worktree| worktree.scan_complete())
 999            .collect::<Vec<_>>();
1000        async move {
1001            for future in futures {
1002                future.await;
1003            }
1004        }
1005    }
1006
1007    pub fn close(
1008        &mut self,
1009        _: &CloseWindow,
1010        cx: &mut ViewContext<Self>,
1011    ) -> Option<Task<Result<()>>> {
1012        let prepare = self.prepare_to_close(cx);
1013        Some(cx.spawn(|this, mut cx| async move {
1014            if prepare.await? {
1015                this.update(&mut cx, |_, cx| {
1016                    let window_id = cx.window_id();
1017                    cx.remove_window(window_id);
1018                });
1019            }
1020            Ok(())
1021        }))
1022    }
1023
1024    pub fn prepare_to_close(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
1025        self.save_all_internal(true, cx)
1026    }
1027
1028    fn save_all(&mut self, _: &SaveAll, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
1029        let save_all = self.save_all_internal(false, cx);
1030        Some(cx.foreground().spawn(async move {
1031            save_all.await?;
1032            Ok(())
1033        }))
1034    }
1035
1036    fn save_all_internal(
1037        &mut self,
1038        should_prompt_to_save: bool,
1039        cx: &mut ViewContext<Self>,
1040    ) -> Task<Result<bool>> {
1041        if self.project.read(cx).is_read_only() {
1042            return Task::ready(Ok(true));
1043        }
1044
1045        let dirty_items = self
1046            .panes
1047            .iter()
1048            .flat_map(|pane| {
1049                pane.read(cx).items().filter_map(|item| {
1050                    if item.is_dirty(cx) {
1051                        Some((pane.clone(), item.boxed_clone()))
1052                    } else {
1053                        None
1054                    }
1055                })
1056            })
1057            .collect::<Vec<_>>();
1058
1059        let project = self.project.clone();
1060        cx.spawn_weak(|_, mut cx| async move {
1061            for (pane, item) in dirty_items {
1062                let (singleton, project_entry_ids) =
1063                    cx.read(|cx| (item.is_singleton(cx), item.project_entry_ids(cx)));
1064                if singleton || !project_entry_ids.is_empty() {
1065                    if let Some(ix) =
1066                        pane.read_with(&cx, |pane, _| pane.index_for_item(item.as_ref()))
1067                    {
1068                        if !Pane::save_item(
1069                            project.clone(),
1070                            &pane,
1071                            ix,
1072                            &item,
1073                            should_prompt_to_save,
1074                            &mut cx,
1075                        )
1076                        .await?
1077                        {
1078                            return Ok(false);
1079                        }
1080                    }
1081                }
1082            }
1083            Ok(true)
1084        })
1085    }
1086
1087    pub fn open_paths(
1088        &mut self,
1089        mut abs_paths: Vec<PathBuf>,
1090        visible: bool,
1091        cx: &mut ViewContext<Self>,
1092    ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
1093        let fs = self.fs.clone();
1094
1095        // Sort the paths to ensure we add worktrees for parents before their children.
1096        abs_paths.sort_unstable();
1097        cx.spawn(|this, mut cx| async move {
1098            let mut project_paths = Vec::new();
1099            for path in &abs_paths {
1100                project_paths.push(
1101                    this.update(&mut cx, |this, cx| {
1102                        this.project_path_for_path(path, visible, cx)
1103                    })
1104                    .await
1105                    .log_err(),
1106                );
1107            }
1108
1109            let tasks = abs_paths
1110                .iter()
1111                .cloned()
1112                .zip(project_paths.into_iter())
1113                .map(|(abs_path, project_path)| {
1114                    let this = this.clone();
1115                    cx.spawn(|mut cx| {
1116                        let fs = fs.clone();
1117                        async move {
1118                            let (_worktree, project_path) = project_path?;
1119                            if fs.is_file(&abs_path).await {
1120                                Some(
1121                                    this.update(&mut cx, |this, cx| {
1122                                        this.open_path(project_path, true, cx)
1123                                    })
1124                                    .await,
1125                                )
1126                            } else {
1127                                None
1128                            }
1129                        }
1130                    })
1131                })
1132                .collect::<Vec<_>>();
1133
1134            futures::future::join_all(tasks).await
1135        })
1136    }
1137
1138    fn add_folder_to_project(&mut self, _: &AddFolderToProject, cx: &mut ViewContext<Self>) {
1139        let mut paths = cx.prompt_for_paths(PathPromptOptions {
1140            files: false,
1141            directories: true,
1142            multiple: true,
1143        });
1144        cx.spawn(|this, mut cx| async move {
1145            if let Some(paths) = paths.recv().await.flatten() {
1146                let results = this
1147                    .update(&mut cx, |this, cx| this.open_paths(paths, true, cx))
1148                    .await;
1149                for result in results {
1150                    if let Some(result) = result {
1151                        result.log_err();
1152                    }
1153                }
1154            }
1155        })
1156        .detach();
1157    }
1158
1159    fn remove_folder_from_project(
1160        &mut self,
1161        RemoveWorktreeFromProject(worktree_id): &RemoveWorktreeFromProject,
1162        cx: &mut ViewContext<Self>,
1163    ) {
1164        self.project
1165            .update(cx, |project, cx| project.remove_worktree(*worktree_id, cx));
1166    }
1167
1168    fn toggle_project_online(&mut self, action: &ToggleProjectOnline, cx: &mut ViewContext<Self>) {
1169        let project = action
1170            .project
1171            .clone()
1172            .unwrap_or_else(|| self.project.clone());
1173        project.update(cx, |project, cx| {
1174            let public = !project.is_online();
1175            project.set_online(public, cx);
1176        });
1177    }
1178
1179    fn project_path_for_path(
1180        &self,
1181        abs_path: &Path,
1182        visible: bool,
1183        cx: &mut ViewContext<Self>,
1184    ) -> Task<Result<(ModelHandle<Worktree>, ProjectPath)>> {
1185        let entry = self.project().update(cx, |project, cx| {
1186            project.find_or_create_local_worktree(abs_path, visible, cx)
1187        });
1188        cx.spawn(|_, cx| async move {
1189            let (worktree, path) = entry.await?;
1190            let worktree_id = worktree.read_with(&cx, |t, _| t.id());
1191            Ok((
1192                worktree,
1193                ProjectPath {
1194                    worktree_id,
1195                    path: path.into(),
1196                },
1197            ))
1198        })
1199    }
1200
1201    /// Returns the modal that was toggled closed if it was open.
1202    pub fn toggle_modal<V, F>(
1203        &mut self,
1204        cx: &mut ViewContext<Self>,
1205        add_view: F,
1206    ) -> Option<ViewHandle<V>>
1207    where
1208        V: 'static + View,
1209        F: FnOnce(&mut Self, &mut ViewContext<Self>) -> ViewHandle<V>,
1210    {
1211        cx.notify();
1212        // Whatever modal was visible is getting clobbered. If its the same type as V, then return
1213        // it. Otherwise, create a new modal and set it as active.
1214        let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
1215        if let Some(already_open_modal) = already_open_modal {
1216            cx.focus_self();
1217            Some(already_open_modal)
1218        } else {
1219            let modal = add_view(self, cx);
1220            cx.focus(&modal);
1221            self.modal = Some(modal.into());
1222            None
1223        }
1224    }
1225
1226    pub fn modal<V: 'static + View>(&self) -> Option<ViewHandle<V>> {
1227        self.modal
1228            .as_ref()
1229            .and_then(|modal| modal.clone().downcast::<V>())
1230    }
1231
1232    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
1233        if self.modal.take().is_some() {
1234            cx.focus(&self.active_pane);
1235            cx.notify();
1236        }
1237    }
1238
1239    pub fn show_notification<V: Notification>(
1240        &mut self,
1241        id: usize,
1242        cx: &mut ViewContext<Self>,
1243        build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
1244    ) {
1245        let type_id = TypeId::of::<V>();
1246        if self
1247            .notifications
1248            .iter()
1249            .all(|(existing_type_id, existing_id, _)| {
1250                (*existing_type_id, *existing_id) != (type_id, id)
1251            })
1252        {
1253            let notification = build_notification(cx);
1254            cx.subscribe(&notification, move |this, handle, event, cx| {
1255                if handle.read(cx).should_dismiss_notification_on_event(event) {
1256                    this.dismiss_notification(type_id, id, cx);
1257                }
1258            })
1259            .detach();
1260            self.notifications
1261                .push((type_id, id, Box::new(notification)));
1262            cx.notify();
1263        }
1264    }
1265
1266    fn dismiss_notification(&mut self, type_id: TypeId, id: usize, cx: &mut ViewContext<Self>) {
1267        self.notifications
1268            .retain(|(existing_type_id, existing_id, _)| {
1269                if (*existing_type_id, *existing_id) == (type_id, id) {
1270                    cx.notify();
1271                    false
1272                } else {
1273                    true
1274                }
1275            });
1276    }
1277
1278    pub fn items<'a>(
1279        &'a self,
1280        cx: &'a AppContext,
1281    ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1282        self.panes.iter().flat_map(|pane| pane.read(cx).items())
1283    }
1284
1285    pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
1286        self.items_of_type(cx).max_by_key(|item| item.id())
1287    }
1288
1289    pub fn items_of_type<'a, T: Item>(
1290        &'a self,
1291        cx: &'a AppContext,
1292    ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
1293        self.panes
1294            .iter()
1295            .flat_map(|pane| pane.read(cx).items_of_type())
1296    }
1297
1298    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1299        self.active_pane().read(cx).active_item()
1300    }
1301
1302    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1303        self.active_item(cx).and_then(|item| item.project_path(cx))
1304    }
1305
1306    pub fn save_active_item(
1307        &mut self,
1308        force_name_change: bool,
1309        cx: &mut ViewContext<Self>,
1310    ) -> Task<Result<()>> {
1311        let project = self.project.clone();
1312        if let Some(item) = self.active_item(cx) {
1313            if !force_name_change && item.can_save(cx) {
1314                if item.has_conflict(cx.as_ref()) {
1315                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1316
1317                    let mut answer = cx.prompt(
1318                        PromptLevel::Warning,
1319                        CONFLICT_MESSAGE,
1320                        &["Overwrite", "Cancel"],
1321                    );
1322                    cx.spawn(|_, mut cx| async move {
1323                        let answer = answer.recv().await;
1324                        if answer == Some(0) {
1325                            cx.update(|cx| item.save(project, cx)).await?;
1326                        }
1327                        Ok(())
1328                    })
1329                } else {
1330                    item.save(project, cx)
1331                }
1332            } else if item.is_singleton(cx) {
1333                let worktree = self.worktrees(cx).next();
1334                let start_abs_path = worktree
1335                    .and_then(|w| w.read(cx).as_local())
1336                    .map_or(Path::new(""), |w| w.abs_path())
1337                    .to_path_buf();
1338                let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1339                cx.spawn(|_, mut cx| async move {
1340                    if let Some(abs_path) = abs_path.recv().await.flatten() {
1341                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1342                    }
1343                    Ok(())
1344                })
1345            } else {
1346                Task::ready(Ok(()))
1347            }
1348        } else {
1349            Task::ready(Ok(()))
1350        }
1351    }
1352
1353    pub fn toggle_sidebar(&mut self, side: Side, cx: &mut ViewContext<Self>) {
1354        let sidebar = match side {
1355            Side::Left => &mut self.left_sidebar,
1356            Side::Right => &mut self.right_sidebar,
1357        };
1358        sidebar.update(cx, |sidebar, cx| {
1359            sidebar.set_open(!sidebar.is_open(), cx);
1360        });
1361        cx.focus_self();
1362        cx.notify();
1363    }
1364
1365    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1366        let sidebar = match action.side {
1367            Side::Left => &mut self.left_sidebar,
1368            Side::Right => &mut self.right_sidebar,
1369        };
1370        let active_item = sidebar.update(cx, |sidebar, cx| {
1371            if sidebar.is_open() && sidebar.active_item_ix() == action.item_index {
1372                sidebar.set_open(false, cx);
1373                None
1374            } else {
1375                sidebar.set_open(true, cx);
1376                sidebar.activate_item(action.item_index, cx);
1377                sidebar.active_item().cloned()
1378            }
1379        });
1380        if let Some(active_item) = active_item {
1381            if active_item.is_focused(cx) {
1382                cx.focus_self();
1383            } else {
1384                cx.focus(active_item.to_any());
1385            }
1386        } else {
1387            cx.focus_self();
1388        }
1389        cx.notify();
1390    }
1391
1392    pub fn toggle_sidebar_item_focus(
1393        &mut self,
1394        side: Side,
1395        item_index: usize,
1396        cx: &mut ViewContext<Self>,
1397    ) {
1398        let sidebar = match side {
1399            Side::Left => &mut self.left_sidebar,
1400            Side::Right => &mut self.right_sidebar,
1401        };
1402        let active_item = sidebar.update(cx, |sidebar, cx| {
1403            sidebar.set_open(true, cx);
1404            sidebar.activate_item(item_index, cx);
1405            sidebar.active_item().cloned()
1406        });
1407        if let Some(active_item) = active_item {
1408            if active_item.is_focused(cx) {
1409                cx.focus_self();
1410            } else {
1411                cx.focus(active_item.to_any());
1412            }
1413        }
1414        cx.notify();
1415    }
1416
1417    pub fn focus_center(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
1418        cx.focus_self();
1419        cx.notify();
1420    }
1421
1422    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1423        let pane = cx.add_view(|cx| Pane::new(cx));
1424        let pane_id = pane.id();
1425        cx.subscribe(&pane, move |this, _, event, cx| {
1426            this.handle_pane_event(pane_id, event, cx)
1427        })
1428        .detach();
1429        self.panes.push(pane.clone());
1430        self.activate_pane(pane.clone(), cx);
1431        cx.emit(Event::PaneAdded(pane.clone()));
1432        pane
1433    }
1434
1435    pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1436        let pane = self.active_pane().clone();
1437        Pane::add_item(self, pane, item, true, true, cx);
1438    }
1439
1440    pub fn open_path(
1441        &mut self,
1442        path: impl Into<ProjectPath>,
1443        focus_item: bool,
1444        cx: &mut ViewContext<Self>,
1445    ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1446        let pane = self.active_pane().downgrade();
1447        let task = self.load_path(path.into(), cx);
1448        cx.spawn(|this, mut cx| async move {
1449            let (project_entry_id, build_item) = task.await?;
1450            let pane = pane
1451                .upgrade(&cx)
1452                .ok_or_else(|| anyhow!("pane was closed"))?;
1453            this.update(&mut cx, |this, cx| {
1454                Ok(Pane::open_item(
1455                    this,
1456                    pane,
1457                    project_entry_id,
1458                    focus_item,
1459                    cx,
1460                    build_item,
1461                ))
1462            })
1463        })
1464    }
1465
1466    pub(crate) fn load_path(
1467        &mut self,
1468        path: ProjectPath,
1469        cx: &mut ViewContext<Self>,
1470    ) -> Task<
1471        Result<(
1472            ProjectEntryId,
1473            impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1474        )>,
1475    > {
1476        let project = self.project().clone();
1477        let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1478        let window_id = cx.window_id();
1479        cx.as_mut().spawn(|mut cx| async move {
1480            let (project_entry_id, project_item) = project_item.await?;
1481            let build_item = cx.update(|cx| {
1482                cx.default_global::<ProjectItemBuilders>()
1483                    .get(&project_item.model_type())
1484                    .ok_or_else(|| anyhow!("no item builder for project item"))
1485                    .cloned()
1486            })?;
1487            let build_item =
1488                move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1489            Ok((project_entry_id, build_item))
1490        })
1491    }
1492
1493    pub fn open_project_item<T>(
1494        &mut self,
1495        project_item: ModelHandle<T::Item>,
1496        cx: &mut ViewContext<Self>,
1497    ) -> ViewHandle<T>
1498    where
1499        T: ProjectItem,
1500    {
1501        use project::Item as _;
1502
1503        let entry_id = project_item.read(cx).entry_id(cx);
1504        if let Some(item) = entry_id
1505            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1506            .and_then(|item| item.downcast())
1507        {
1508            self.activate_item(&item, cx);
1509            return item;
1510        }
1511
1512        let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1513        self.add_item(Box::new(item.clone()), cx);
1514        item
1515    }
1516
1517    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1518        let result = self.panes.iter().find_map(|pane| {
1519            if let Some(ix) = pane.read(cx).index_for_item(item) {
1520                Some((pane.clone(), ix))
1521            } else {
1522                None
1523            }
1524        });
1525        if let Some((pane, ix)) = result {
1526            self.activate_pane(pane.clone(), cx);
1527            pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, false, cx));
1528            true
1529        } else {
1530            false
1531        }
1532    }
1533
1534    fn activate_pane_at_index(&mut self, action: &ActivatePane, cx: &mut ViewContext<Self>) {
1535        let panes = self.center.panes();
1536        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
1537            self.activate_pane(pane, cx);
1538        } else {
1539            self.split_pane(self.active_pane.clone(), SplitDirection::Right, cx);
1540        }
1541    }
1542
1543    pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1544        let next_pane = {
1545            let panes = self.center.panes();
1546            let ix = panes
1547                .iter()
1548                .position(|pane| **pane == self.active_pane)
1549                .unwrap();
1550            let next_ix = (ix + 1) % panes.len();
1551            panes[next_ix].clone()
1552        };
1553        self.activate_pane(next_pane, cx);
1554    }
1555
1556    pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1557        let prev_pane = {
1558            let panes = self.center.panes();
1559            let ix = panes
1560                .iter()
1561                .position(|pane| **pane == self.active_pane)
1562                .unwrap();
1563            let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1564            panes[prev_ix].clone()
1565        };
1566        self.activate_pane(prev_pane, cx);
1567    }
1568
1569    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1570        if self.active_pane != pane {
1571            self.active_pane
1572                .update(cx, |pane, cx| pane.set_active(false, cx));
1573            self.active_pane = pane.clone();
1574            self.active_pane
1575                .update(cx, |pane, cx| pane.set_active(true, cx));
1576            self.status_bar.update(cx, |status_bar, cx| {
1577                status_bar.set_active_pane(&self.active_pane, cx);
1578            });
1579            self.active_item_path_changed(cx);
1580            cx.focus(&self.active_pane);
1581            cx.notify();
1582        }
1583
1584        self.update_followers(
1585            proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1586                id: self.active_item(cx).map(|item| item.id() as u64),
1587                leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1588            }),
1589            cx,
1590        );
1591    }
1592
1593    fn handle_pane_event(
1594        &mut self,
1595        pane_id: usize,
1596        event: &pane::Event,
1597        cx: &mut ViewContext<Self>,
1598    ) {
1599        if let Some(pane) = self.pane(pane_id) {
1600            match event {
1601                pane::Event::Split(direction) => {
1602                    self.split_pane(pane, *direction, cx);
1603                }
1604                pane::Event::Remove => {
1605                    self.remove_pane(pane, cx);
1606                }
1607                pane::Event::Activate => {
1608                    self.activate_pane(pane, cx);
1609                }
1610                pane::Event::ActivateItem { local } => {
1611                    if *local {
1612                        self.unfollow(&pane, cx);
1613                    }
1614                    if pane == self.active_pane {
1615                        self.active_item_path_changed(cx);
1616                    }
1617                }
1618                pane::Event::ChangeItemTitle => {
1619                    if pane == self.active_pane {
1620                        self.active_item_path_changed(cx);
1621                    }
1622                    self.update_window_edited(cx);
1623                }
1624                pane::Event::RemoveItem => {
1625                    self.update_window_edited(cx);
1626                }
1627            }
1628        } else {
1629            error!("pane {} not found", pane_id);
1630        }
1631    }
1632
1633    pub fn split_pane(
1634        &mut self,
1635        pane: ViewHandle<Pane>,
1636        direction: SplitDirection,
1637        cx: &mut ViewContext<Self>,
1638    ) -> Option<ViewHandle<Pane>> {
1639        pane.read(cx).active_item().map(|item| {
1640            let new_pane = self.add_pane(cx);
1641            self.activate_pane(new_pane.clone(), cx);
1642            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1643                Pane::add_item(self, new_pane.clone(), clone, true, true, cx);
1644            }
1645            self.center.split(&pane, &new_pane, direction).unwrap();
1646            cx.notify();
1647            new_pane
1648        })
1649    }
1650
1651    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1652        if self.center.remove(&pane).unwrap() {
1653            self.panes.retain(|p| p != &pane);
1654            self.activate_pane(self.panes.last().unwrap().clone(), cx);
1655            self.unfollow(&pane, cx);
1656            self.last_leaders_by_pane.remove(&pane.downgrade());
1657            cx.notify();
1658        } else {
1659            self.active_item_path_changed(cx);
1660        }
1661    }
1662
1663    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1664        &self.panes
1665    }
1666
1667    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1668        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1669    }
1670
1671    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1672        &self.active_pane
1673    }
1674
1675    fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1676        if let Some(remote_id) = remote_id {
1677            self.remote_entity_subscription =
1678                Some(self.client.add_view_for_remote_entity(remote_id, cx));
1679        } else {
1680            self.remote_entity_subscription.take();
1681        }
1682    }
1683
1684    fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1685        self.leader_state.followers.remove(&peer_id);
1686        if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1687            for state in states_by_pane.into_values() {
1688                for item in state.items_by_leader_view_id.into_values() {
1689                    if let FollowerItem::Loaded(item) = item {
1690                        item.set_leader_replica_id(None, cx);
1691                    }
1692                }
1693            }
1694        }
1695        cx.notify();
1696    }
1697
1698    pub fn toggle_follow(
1699        &mut self,
1700        ToggleFollow(leader_id): &ToggleFollow,
1701        cx: &mut ViewContext<Self>,
1702    ) -> Option<Task<Result<()>>> {
1703        let leader_id = *leader_id;
1704        let pane = self.active_pane().clone();
1705
1706        if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1707            if leader_id == prev_leader_id {
1708                return None;
1709            }
1710        }
1711
1712        self.last_leaders_by_pane
1713            .insert(pane.downgrade(), leader_id);
1714        self.follower_states_by_leader
1715            .entry(leader_id)
1716            .or_default()
1717            .insert(pane.clone(), Default::default());
1718        cx.notify();
1719
1720        let project_id = self.project.read(cx).remote_id()?;
1721        let request = self.client.request(proto::Follow {
1722            project_id,
1723            leader_id: leader_id.0,
1724        });
1725        Some(cx.spawn_weak(|this, mut cx| async move {
1726            let response = request.await?;
1727            if let Some(this) = this.upgrade(&cx) {
1728                this.update(&mut cx, |this, _| {
1729                    let state = this
1730                        .follower_states_by_leader
1731                        .get_mut(&leader_id)
1732                        .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1733                        .ok_or_else(|| anyhow!("following interrupted"))?;
1734                    state.active_view_id = response.active_view_id;
1735                    Ok::<_, anyhow::Error>(())
1736                })?;
1737                Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1738                    .await?;
1739            }
1740            Ok(())
1741        }))
1742    }
1743
1744    pub fn follow_next_collaborator(
1745        &mut self,
1746        _: &FollowNextCollaborator,
1747        cx: &mut ViewContext<Self>,
1748    ) -> Option<Task<Result<()>>> {
1749        let collaborators = self.project.read(cx).collaborators();
1750        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1751            let mut collaborators = collaborators.keys().copied();
1752            while let Some(peer_id) = collaborators.next() {
1753                if peer_id == leader_id {
1754                    break;
1755                }
1756            }
1757            collaborators.next()
1758        } else if let Some(last_leader_id) =
1759            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1760        {
1761            if collaborators.contains_key(last_leader_id) {
1762                Some(*last_leader_id)
1763            } else {
1764                None
1765            }
1766        } else {
1767            None
1768        };
1769
1770        next_leader_id
1771            .or_else(|| collaborators.keys().copied().next())
1772            .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1773    }
1774
1775    pub fn unfollow(
1776        &mut self,
1777        pane: &ViewHandle<Pane>,
1778        cx: &mut ViewContext<Self>,
1779    ) -> Option<PeerId> {
1780        for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1781            let leader_id = *leader_id;
1782            if let Some(state) = states_by_pane.remove(&pane) {
1783                for (_, item) in state.items_by_leader_view_id {
1784                    if let FollowerItem::Loaded(item) = item {
1785                        item.set_leader_replica_id(None, cx);
1786                    }
1787                }
1788
1789                if states_by_pane.is_empty() {
1790                    self.follower_states_by_leader.remove(&leader_id);
1791                    if let Some(project_id) = self.project.read(cx).remote_id() {
1792                        self.client
1793                            .send(proto::Unfollow {
1794                                project_id,
1795                                leader_id: leader_id.0,
1796                            })
1797                            .log_err();
1798                    }
1799                }
1800
1801                cx.notify();
1802                return Some(leader_id);
1803            }
1804        }
1805        None
1806    }
1807
1808    fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1809        let theme = &cx.global::<Settings>().theme;
1810        match &*self.client.status().borrow() {
1811            client::Status::ConnectionError
1812            | client::Status::ConnectionLost
1813            | client::Status::Reauthenticating
1814            | client::Status::Reconnecting { .. }
1815            | client::Status::ReconnectionError { .. } => Some(
1816                Container::new(
1817                    Align::new(
1818                        ConstrainedBox::new(
1819                            Svg::new("icons/cloud_slash_12.svg")
1820                                .with_color(theme.workspace.titlebar.offline_icon.color)
1821                                .boxed(),
1822                        )
1823                        .with_width(theme.workspace.titlebar.offline_icon.width)
1824                        .boxed(),
1825                    )
1826                    .boxed(),
1827                )
1828                .with_style(theme.workspace.titlebar.offline_icon.container)
1829                .boxed(),
1830            ),
1831            client::Status::UpgradeRequired => Some(
1832                Label::new(
1833                    "Please update Zed to collaborate".to_string(),
1834                    theme.workspace.titlebar.outdated_warning.text.clone(),
1835                )
1836                .contained()
1837                .with_style(theme.workspace.titlebar.outdated_warning.container)
1838                .aligned()
1839                .boxed(),
1840            ),
1841            _ => None,
1842        }
1843    }
1844
1845    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1846        let project = &self.project.read(cx);
1847        let replica_id = project.replica_id();
1848        let mut worktree_root_names = String::new();
1849        for (i, name) in project.worktree_root_names(cx).enumerate() {
1850            if i > 0 {
1851                worktree_root_names.push_str(", ");
1852            }
1853            worktree_root_names.push_str(name);
1854        }
1855
1856        ConstrainedBox::new(
1857            Container::new(
1858                Stack::new()
1859                    .with_child(
1860                        Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
1861                            .aligned()
1862                            .left()
1863                            .boxed(),
1864                    )
1865                    .with_child(
1866                        Align::new(
1867                            Flex::row()
1868                                .with_children(self.render_collaborators(theme, cx))
1869                                .with_children(self.render_current_user(
1870                                    self.user_store.read(cx).current_user().as_ref(),
1871                                    replica_id,
1872                                    theme,
1873                                    cx,
1874                                ))
1875                                .with_children(self.render_connection_status(cx))
1876                                .boxed(),
1877                        )
1878                        .right()
1879                        .boxed(),
1880                    )
1881                    .boxed(),
1882            )
1883            .with_style(theme.workspace.titlebar.container)
1884            .boxed(),
1885        )
1886        .with_height(theme.workspace.titlebar.height)
1887        .named("titlebar")
1888    }
1889
1890    fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
1891        let active_entry = self.active_project_path(cx);
1892        self.project
1893            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1894        self.update_window_title(cx);
1895    }
1896
1897    fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
1898        let mut title = String::new();
1899        let project = self.project().read(cx);
1900        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
1901            let filename = path
1902                .path
1903                .file_name()
1904                .map(|s| s.to_string_lossy())
1905                .or_else(|| {
1906                    Some(Cow::Borrowed(
1907                        project
1908                            .worktree_for_id(path.worktree_id, cx)?
1909                            .read(cx)
1910                            .root_name(),
1911                    ))
1912                });
1913            if let Some(filename) = filename {
1914                title.push_str(filename.as_ref());
1915                title.push_str("");
1916            }
1917        }
1918        for (i, name) in project.worktree_root_names(cx).enumerate() {
1919            if i > 0 {
1920                title.push_str(", ");
1921            }
1922            title.push_str(name);
1923        }
1924        if title.is_empty() {
1925            title = "empty project".to_string();
1926        }
1927        cx.set_window_title(&title);
1928    }
1929
1930    fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
1931        let is_edited = !self.project.read(cx).is_read_only()
1932            && self
1933                .items(cx)
1934                .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
1935        if is_edited != self.window_edited {
1936            self.window_edited = is_edited;
1937            cx.set_window_edited(self.window_edited)
1938        }
1939    }
1940
1941    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1942        let mut collaborators = self
1943            .project
1944            .read(cx)
1945            .collaborators()
1946            .values()
1947            .cloned()
1948            .collect::<Vec<_>>();
1949        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1950        collaborators
1951            .into_iter()
1952            .filter_map(|collaborator| {
1953                Some(self.render_avatar(
1954                    collaborator.user.avatar.clone()?,
1955                    collaborator.replica_id,
1956                    Some((collaborator.peer_id, &collaborator.user.github_login)),
1957                    theme,
1958                    cx,
1959                ))
1960            })
1961            .collect()
1962    }
1963
1964    fn render_current_user(
1965        &self,
1966        user: Option<&Arc<User>>,
1967        replica_id: ReplicaId,
1968        theme: &Theme,
1969        cx: &mut RenderContext<Self>,
1970    ) -> Option<ElementBox> {
1971        let status = *self.client.status().borrow();
1972        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1973            Some(self.render_avatar(avatar, replica_id, None, theme, cx))
1974        } else if matches!(status, client::Status::UpgradeRequired) {
1975            None
1976        } else {
1977            Some(
1978                MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1979                    let style = theme
1980                        .workspace
1981                        .titlebar
1982                        .sign_in_prompt
1983                        .style_for(state, false);
1984                    Label::new("Sign in".to_string(), style.text.clone())
1985                        .contained()
1986                        .with_style(style.container)
1987                        .boxed()
1988                })
1989                .on_click(MouseButton::Left, |_, cx| cx.dispatch_action(Authenticate))
1990                .with_cursor_style(CursorStyle::PointingHand)
1991                .aligned()
1992                .boxed(),
1993            )
1994        }
1995    }
1996
1997    fn render_avatar(
1998        &self,
1999        avatar: Arc<ImageData>,
2000        replica_id: ReplicaId,
2001        peer: Option<(PeerId, &str)>,
2002        theme: &Theme,
2003        cx: &mut RenderContext<Self>,
2004    ) -> ElementBox {
2005        let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
2006        let is_followed = peer.map_or(false, |(peer_id, _)| {
2007            self.follower_states_by_leader.contains_key(&peer_id)
2008        });
2009        let mut avatar_style = theme.workspace.titlebar.avatar;
2010        if is_followed {
2011            avatar_style.border = Border::all(1.0, replica_color);
2012        }
2013        let content = Stack::new()
2014            .with_child(
2015                Image::new(avatar)
2016                    .with_style(avatar_style)
2017                    .constrained()
2018                    .with_width(theme.workspace.titlebar.avatar_width)
2019                    .aligned()
2020                    .boxed(),
2021            )
2022            .with_child(
2023                AvatarRibbon::new(replica_color)
2024                    .constrained()
2025                    .with_width(theme.workspace.titlebar.avatar_ribbon.width)
2026                    .with_height(theme.workspace.titlebar.avatar_ribbon.height)
2027                    .aligned()
2028                    .bottom()
2029                    .boxed(),
2030            )
2031            .constrained()
2032            .with_width(theme.workspace.titlebar.avatar_width)
2033            .contained()
2034            .with_margin_left(theme.workspace.titlebar.avatar_margin)
2035            .boxed();
2036
2037        if let Some((peer_id, peer_github_login)) = peer {
2038            MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
2039                .with_cursor_style(CursorStyle::PointingHand)
2040                .on_click(MouseButton::Left, move |_, cx| {
2041                    cx.dispatch_action(ToggleFollow(peer_id))
2042                })
2043                .with_tooltip::<ToggleFollow, _>(
2044                    peer_id.0 as usize,
2045                    if is_followed {
2046                        format!("Unfollow {}", peer_github_login)
2047                    } else {
2048                        format!("Follow {}", peer_github_login)
2049                    },
2050                    Some(Box::new(FollowNextCollaborator)),
2051                    theme.tooltip.clone(),
2052                    cx,
2053                )
2054                .boxed()
2055        } else {
2056            content
2057        }
2058    }
2059
2060    fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
2061        if self.project.read(cx).is_read_only() {
2062            let theme = &cx.global::<Settings>().theme;
2063            Some(
2064                EventHandler::new(
2065                    Label::new(
2066                        "Your connection to the remote project has been lost.".to_string(),
2067                        theme.workspace.disconnected_overlay.text.clone(),
2068                    )
2069                    .aligned()
2070                    .contained()
2071                    .with_style(theme.workspace.disconnected_overlay.container)
2072                    .boxed(),
2073                )
2074                .capture_all::<Self>(0)
2075                .boxed(),
2076            )
2077        } else {
2078            None
2079        }
2080    }
2081
2082    fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
2083        if self.notifications.is_empty() {
2084            None
2085        } else {
2086            Some(
2087                Flex::column()
2088                    .with_children(self.notifications.iter().map(|(_, _, notification)| {
2089                        ChildView::new(notification.as_ref())
2090                            .contained()
2091                            .with_style(theme.notification)
2092                            .boxed()
2093                    }))
2094                    .constrained()
2095                    .with_width(theme.notifications.width)
2096                    .contained()
2097                    .with_style(theme.notifications.container)
2098                    .aligned()
2099                    .bottom()
2100                    .right()
2101                    .boxed(),
2102            )
2103        }
2104    }
2105
2106    // RPC handlers
2107
2108    async fn handle_follow(
2109        this: ViewHandle<Self>,
2110        envelope: TypedEnvelope<proto::Follow>,
2111        _: Arc<Client>,
2112        mut cx: AsyncAppContext,
2113    ) -> Result<proto::FollowResponse> {
2114        this.update(&mut cx, |this, cx| {
2115            this.leader_state
2116                .followers
2117                .insert(envelope.original_sender_id()?);
2118
2119            let active_view_id = this
2120                .active_item(cx)
2121                .and_then(|i| i.to_followable_item_handle(cx))
2122                .map(|i| i.id() as u64);
2123            Ok(proto::FollowResponse {
2124                active_view_id,
2125                views: this
2126                    .panes()
2127                    .iter()
2128                    .flat_map(|pane| {
2129                        let leader_id = this.leader_for_pane(pane).map(|id| id.0);
2130                        pane.read(cx).items().filter_map({
2131                            let cx = &cx;
2132                            move |item| {
2133                                let id = item.id() as u64;
2134                                let item = item.to_followable_item_handle(cx)?;
2135                                let variant = item.to_state_proto(cx)?;
2136                                Some(proto::View {
2137                                    id,
2138                                    leader_id,
2139                                    variant: Some(variant),
2140                                })
2141                            }
2142                        })
2143                    })
2144                    .collect(),
2145            })
2146        })
2147    }
2148
2149    async fn handle_unfollow(
2150        this: ViewHandle<Self>,
2151        envelope: TypedEnvelope<proto::Unfollow>,
2152        _: Arc<Client>,
2153        mut cx: AsyncAppContext,
2154    ) -> Result<()> {
2155        this.update(&mut cx, |this, _| {
2156            this.leader_state
2157                .followers
2158                .remove(&envelope.original_sender_id()?);
2159            Ok(())
2160        })
2161    }
2162
2163    async fn handle_update_followers(
2164        this: ViewHandle<Self>,
2165        envelope: TypedEnvelope<proto::UpdateFollowers>,
2166        _: Arc<Client>,
2167        mut cx: AsyncAppContext,
2168    ) -> Result<()> {
2169        let leader_id = envelope.original_sender_id()?;
2170        match envelope
2171            .payload
2172            .variant
2173            .ok_or_else(|| anyhow!("invalid update"))?
2174        {
2175            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2176                this.update(&mut cx, |this, cx| {
2177                    this.update_leader_state(leader_id, cx, |state, _| {
2178                        state.active_view_id = update_active_view.id;
2179                    });
2180                    Ok::<_, anyhow::Error>(())
2181                })
2182            }
2183            proto::update_followers::Variant::UpdateView(update_view) => {
2184                this.update(&mut cx, |this, cx| {
2185                    let variant = update_view
2186                        .variant
2187                        .ok_or_else(|| anyhow!("missing update view variant"))?;
2188                    this.update_leader_state(leader_id, cx, |state, cx| {
2189                        let variant = variant.clone();
2190                        match state
2191                            .items_by_leader_view_id
2192                            .entry(update_view.id)
2193                            .or_insert(FollowerItem::Loading(Vec::new()))
2194                        {
2195                            FollowerItem::Loaded(item) => {
2196                                item.apply_update_proto(variant, cx).log_err();
2197                            }
2198                            FollowerItem::Loading(updates) => updates.push(variant),
2199                        }
2200                    });
2201                    Ok(())
2202                })
2203            }
2204            proto::update_followers::Variant::CreateView(view) => {
2205                let panes = this.read_with(&cx, |this, _| {
2206                    this.follower_states_by_leader
2207                        .get(&leader_id)
2208                        .into_iter()
2209                        .flat_map(|states_by_pane| states_by_pane.keys())
2210                        .cloned()
2211                        .collect()
2212                });
2213                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
2214                    .await?;
2215                Ok(())
2216            }
2217        }
2218        .log_err();
2219
2220        Ok(())
2221    }
2222
2223    async fn add_views_from_leader(
2224        this: ViewHandle<Self>,
2225        leader_id: PeerId,
2226        panes: Vec<ViewHandle<Pane>>,
2227        views: Vec<proto::View>,
2228        cx: &mut AsyncAppContext,
2229    ) -> Result<()> {
2230        let project = this.read_with(cx, |this, _| this.project.clone());
2231        let replica_id = project
2232            .read_with(cx, |project, _| {
2233                project
2234                    .collaborators()
2235                    .get(&leader_id)
2236                    .map(|c| c.replica_id)
2237            })
2238            .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
2239
2240        let item_builders = cx.update(|cx| {
2241            cx.default_global::<FollowableItemBuilders>()
2242                .values()
2243                .map(|b| b.0)
2244                .collect::<Vec<_>>()
2245                .clone()
2246        });
2247
2248        let mut item_tasks_by_pane = HashMap::default();
2249        for pane in panes {
2250            let mut item_tasks = Vec::new();
2251            let mut leader_view_ids = Vec::new();
2252            for view in &views {
2253                let mut variant = view.variant.clone();
2254                if variant.is_none() {
2255                    Err(anyhow!("missing variant"))?;
2256                }
2257                for build_item in &item_builders {
2258                    let task =
2259                        cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
2260                    if let Some(task) = task {
2261                        item_tasks.push(task);
2262                        leader_view_ids.push(view.id);
2263                        break;
2264                    } else {
2265                        assert!(variant.is_some());
2266                    }
2267                }
2268            }
2269
2270            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2271        }
2272
2273        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2274            let items = futures::future::try_join_all(item_tasks).await?;
2275            this.update(cx, |this, cx| {
2276                let state = this
2277                    .follower_states_by_leader
2278                    .get_mut(&leader_id)?
2279                    .get_mut(&pane)?;
2280
2281                for (id, item) in leader_view_ids.into_iter().zip(items) {
2282                    item.set_leader_replica_id(Some(replica_id), cx);
2283                    match state.items_by_leader_view_id.entry(id) {
2284                        hash_map::Entry::Occupied(e) => {
2285                            let e = e.into_mut();
2286                            if let FollowerItem::Loading(updates) = e {
2287                                for update in updates.drain(..) {
2288                                    item.apply_update_proto(update, cx)
2289                                        .context("failed to apply view update")
2290                                        .log_err();
2291                                }
2292                            }
2293                            *e = FollowerItem::Loaded(item);
2294                        }
2295                        hash_map::Entry::Vacant(e) => {
2296                            e.insert(FollowerItem::Loaded(item));
2297                        }
2298                    }
2299                }
2300
2301                Some(())
2302            });
2303        }
2304        this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
2305
2306        Ok(())
2307    }
2308
2309    fn update_followers(
2310        &self,
2311        update: proto::update_followers::Variant,
2312        cx: &AppContext,
2313    ) -> Option<()> {
2314        let project_id = self.project.read(cx).remote_id()?;
2315        if !self.leader_state.followers.is_empty() {
2316            self.client
2317                .send(proto::UpdateFollowers {
2318                    project_id,
2319                    follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
2320                    variant: Some(update),
2321                })
2322                .log_err();
2323        }
2324        None
2325    }
2326
2327    pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
2328        self.follower_states_by_leader
2329            .iter()
2330            .find_map(|(leader_id, state)| {
2331                if state.contains_key(pane) {
2332                    Some(*leader_id)
2333                } else {
2334                    None
2335                }
2336            })
2337    }
2338
2339    fn update_leader_state(
2340        &mut self,
2341        leader_id: PeerId,
2342        cx: &mut ViewContext<Self>,
2343        mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
2344    ) {
2345        for (_, state) in self
2346            .follower_states_by_leader
2347            .get_mut(&leader_id)
2348            .into_iter()
2349            .flatten()
2350        {
2351            update_fn(state, cx);
2352        }
2353        self.leader_updated(leader_id, cx);
2354    }
2355
2356    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2357        let mut items_to_add = Vec::new();
2358        for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2359            if let Some(active_item) = state
2360                .active_view_id
2361                .and_then(|id| state.items_by_leader_view_id.get(&id))
2362            {
2363                if let FollowerItem::Loaded(item) = active_item {
2364                    items_to_add.push((pane.clone(), item.boxed_clone()));
2365                }
2366            }
2367        }
2368
2369        for (pane, item) in items_to_add {
2370            Pane::add_item(self, pane.clone(), item.boxed_clone(), false, false, cx);
2371            if pane == self.active_pane {
2372                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2373            }
2374            cx.notify();
2375        }
2376        None
2377    }
2378
2379    fn on_window_activation_changed(&mut self, active: bool, cx: &mut ViewContext<Self>) {
2380        if !active
2381            && matches!(
2382                cx.global::<Settings>().autosave,
2383                Autosave::OnWindowChange | Autosave::OnFocusChange
2384            )
2385        {
2386            for pane in &self.panes {
2387                pane.update(cx, |pane, cx| {
2388                    for item in pane.items() {
2389                        Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
2390                            .detach_and_log_err(cx);
2391                    }
2392                });
2393            }
2394        }
2395    }
2396}
2397
2398impl Entity for Workspace {
2399    type Event = Event;
2400}
2401
2402impl View for Workspace {
2403    fn ui_name() -> &'static str {
2404        "Workspace"
2405    }
2406
2407    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2408        let theme = cx.global::<Settings>().theme.clone();
2409        Stack::new()
2410            .with_child(
2411                Flex::column()
2412                    .with_child(self.render_titlebar(&theme, cx))
2413                    .with_child(
2414                        Stack::new()
2415                            .with_child({
2416                                Flex::row()
2417                                    .with_children(
2418                                        if self.left_sidebar.read(cx).active_item().is_some() {
2419                                            Some(
2420                                                ChildView::new(&self.left_sidebar)
2421                                                    .flex(0.8, false)
2422                                                    .boxed(),
2423                                            )
2424                                        } else {
2425                                            None
2426                                        },
2427                                    )
2428                                    .with_child(
2429                                        FlexItem::new(self.center.render(
2430                                            &theme,
2431                                            &self.follower_states_by_leader,
2432                                            self.project.read(cx).collaborators(),
2433                                        ))
2434                                        .flex(1., true)
2435                                        .boxed(),
2436                                    )
2437                                    .with_children(
2438                                        if self.right_sidebar.read(cx).active_item().is_some() {
2439                                            Some(
2440                                                ChildView::new(&self.right_sidebar)
2441                                                    .flex(0.8, false)
2442                                                    .boxed(),
2443                                            )
2444                                        } else {
2445                                            None
2446                                        },
2447                                    )
2448                                    .boxed()
2449                            })
2450                            .with_children(self.modal.as_ref().map(|m| {
2451                                ChildView::new(m)
2452                                    .contained()
2453                                    .with_style(theme.workspace.modal)
2454                                    .aligned()
2455                                    .top()
2456                                    .boxed()
2457                            }))
2458                            .with_children(self.render_notifications(&theme.workspace))
2459                            .flex(1.0, true)
2460                            .boxed(),
2461                    )
2462                    .with_child(ChildView::new(&self.status_bar).boxed())
2463                    .contained()
2464                    .with_background_color(theme.workspace.background)
2465                    .boxed(),
2466            )
2467            .with_children(self.render_disconnected_overlay(cx))
2468            .named("workspace")
2469    }
2470
2471    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2472        cx.focus(&self.active_pane);
2473    }
2474}
2475
2476pub trait WorkspaceHandle {
2477    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2478}
2479
2480impl WorkspaceHandle for ViewHandle<Workspace> {
2481    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2482        self.read(cx)
2483            .worktrees(cx)
2484            .flat_map(|worktree| {
2485                let worktree_id = worktree.read(cx).id();
2486                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2487                    worktree_id,
2488                    path: f.path.clone(),
2489                })
2490            })
2491            .collect::<Vec<_>>()
2492    }
2493}
2494
2495pub struct AvatarRibbon {
2496    color: Color,
2497}
2498
2499impl AvatarRibbon {
2500    pub fn new(color: Color) -> AvatarRibbon {
2501        AvatarRibbon { color }
2502    }
2503}
2504
2505impl Element for AvatarRibbon {
2506    type LayoutState = ();
2507
2508    type PaintState = ();
2509
2510    fn layout(
2511        &mut self,
2512        constraint: gpui::SizeConstraint,
2513        _: &mut gpui::LayoutContext,
2514    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2515        (constraint.max, ())
2516    }
2517
2518    fn paint(
2519        &mut self,
2520        bounds: gpui::geometry::rect::RectF,
2521        _: gpui::geometry::rect::RectF,
2522        _: &mut Self::LayoutState,
2523        cx: &mut gpui::PaintContext,
2524    ) -> Self::PaintState {
2525        let mut path = PathBuilder::new();
2526        path.reset(bounds.lower_left());
2527        path.curve_to(
2528            bounds.origin() + vec2f(bounds.height(), 0.),
2529            bounds.origin(),
2530        );
2531        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2532        path.curve_to(bounds.lower_right(), bounds.upper_right());
2533        path.line_to(bounds.lower_left());
2534        cx.scene.push_path(path.build(self.color, None));
2535    }
2536
2537    fn dispatch_event(
2538        &mut self,
2539        _: &gpui::Event,
2540        _: RectF,
2541        _: RectF,
2542        _: &mut Self::LayoutState,
2543        _: &mut Self::PaintState,
2544        _: &mut gpui::EventContext,
2545    ) -> bool {
2546        false
2547    }
2548
2549    fn debug(
2550        &self,
2551        bounds: gpui::geometry::rect::RectF,
2552        _: &Self::LayoutState,
2553        _: &Self::PaintState,
2554        _: &gpui::DebugContext,
2555    ) -> gpui::json::Value {
2556        json::json!({
2557            "type": "AvatarRibbon",
2558            "bounds": bounds.to_json(),
2559            "color": self.color.to_json(),
2560        })
2561    }
2562}
2563
2564impl std::fmt::Debug for OpenPaths {
2565    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2566        f.debug_struct("OpenPaths")
2567            .field("paths", &self.paths)
2568            .finish()
2569    }
2570}
2571
2572fn open(_: &Open, cx: &mut MutableAppContext) {
2573    let mut paths = cx.prompt_for_paths(PathPromptOptions {
2574        files: true,
2575        directories: true,
2576        multiple: true,
2577    });
2578    cx.spawn(|mut cx| async move {
2579        if let Some(paths) = paths.recv().await.flatten() {
2580            cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2581        }
2582    })
2583    .detach();
2584}
2585
2586pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2587
2588pub fn activate_workspace_for_project(
2589    cx: &mut MutableAppContext,
2590    predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2591) -> Option<ViewHandle<Workspace>> {
2592    for window_id in cx.window_ids().collect::<Vec<_>>() {
2593        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2594            let project = workspace_handle.read(cx).project.clone();
2595            if project.update(cx, &predicate) {
2596                cx.activate_window(window_id);
2597                return Some(workspace_handle);
2598            }
2599        }
2600    }
2601    None
2602}
2603
2604pub fn open_paths(
2605    abs_paths: &[PathBuf],
2606    app_state: &Arc<AppState>,
2607    cx: &mut MutableAppContext,
2608) -> Task<(
2609    ViewHandle<Workspace>,
2610    Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2611)> {
2612    log::info!("open paths {:?}", abs_paths);
2613
2614    // Open paths in existing workspace if possible
2615    let existing =
2616        activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2617
2618    let app_state = app_state.clone();
2619    let abs_paths = abs_paths.to_vec();
2620    cx.spawn(|mut cx| async move {
2621        let mut new_project = None;
2622        let workspace = if let Some(existing) = existing {
2623            existing
2624        } else {
2625            let contains_directory =
2626                futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2627                    .await
2628                    .contains(&false);
2629
2630            cx.add_window((app_state.build_window_options)(), |cx| {
2631                let project = Project::local(
2632                    false,
2633                    app_state.client.clone(),
2634                    app_state.user_store.clone(),
2635                    app_state.project_store.clone(),
2636                    app_state.languages.clone(),
2637                    app_state.fs.clone(),
2638                    cx,
2639                );
2640                new_project = Some(project.clone());
2641                let mut workspace = Workspace::new(project, cx);
2642                (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2643                if contains_directory {
2644                    workspace.toggle_sidebar(Side::Left, cx);
2645                }
2646                workspace
2647            })
2648            .1
2649        };
2650
2651        let items = workspace
2652            .update(&mut cx, |workspace, cx| {
2653                workspace.open_paths(abs_paths, true, cx)
2654            })
2655            .await;
2656
2657        if let Some(project) = new_project {
2658            project
2659                .update(&mut cx, |project, cx| project.restore_state(cx))
2660                .await
2661                .log_err();
2662        }
2663
2664        (workspace, items)
2665    })
2666}
2667
2668pub fn join_project(
2669    contact: Arc<Contact>,
2670    project_index: usize,
2671    app_state: &Arc<AppState>,
2672    cx: &mut MutableAppContext,
2673) {
2674    let project_id = contact.projects[project_index].id;
2675
2676    for window_id in cx.window_ids().collect::<Vec<_>>() {
2677        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2678            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2679                cx.activate_window(window_id);
2680                return;
2681            }
2682        }
2683    }
2684
2685    cx.add_window((app_state.build_window_options)(), |cx| {
2686        WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2687    });
2688}
2689
2690fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2691    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2692        let mut workspace = Workspace::new(
2693            Project::local(
2694                false,
2695                app_state.client.clone(),
2696                app_state.user_store.clone(),
2697                app_state.project_store.clone(),
2698                app_state.languages.clone(),
2699                app_state.fs.clone(),
2700                cx,
2701            ),
2702            cx,
2703        );
2704        (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2705        workspace
2706    });
2707    cx.dispatch_action(window_id, vec![workspace.id()], &NewFile);
2708}
2709
2710#[cfg(test)]
2711mod tests {
2712    use std::cell::Cell;
2713
2714    use super::*;
2715    use gpui::{executor::Deterministic, ModelHandle, TestAppContext, ViewContext};
2716    use project::{FakeFs, Project, ProjectEntryId};
2717    use serde_json::json;
2718
2719    #[gpui::test]
2720    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
2721        cx.foreground().forbid_parking();
2722        Settings::test_async(cx);
2723
2724        let fs = FakeFs::new(cx.background());
2725        let project = Project::test(fs, [], cx).await;
2726        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2727
2728        // Adding an item with no ambiguity renders the tab without detail.
2729        let item1 = cx.add_view(window_id, |_| {
2730            let mut item = TestItem::new();
2731            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
2732            item
2733        });
2734        workspace.update(cx, |workspace, cx| {
2735            workspace.add_item(Box::new(item1.clone()), cx);
2736        });
2737        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
2738
2739        // Adding an item that creates ambiguity increases the level of detail on
2740        // both tabs.
2741        let item2 = cx.add_view(window_id, |_| {
2742            let mut item = TestItem::new();
2743            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2744            item
2745        });
2746        workspace.update(cx, |workspace, cx| {
2747            workspace.add_item(Box::new(item2.clone()), cx);
2748        });
2749        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2750        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2751
2752        // Adding an item that creates ambiguity increases the level of detail only
2753        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
2754        // we stop at the highest detail available.
2755        let item3 = cx.add_view(window_id, |_| {
2756            let mut item = TestItem::new();
2757            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2758            item
2759        });
2760        workspace.update(cx, |workspace, cx| {
2761            workspace.add_item(Box::new(item3.clone()), cx);
2762        });
2763        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2764        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2765        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2766    }
2767
2768    #[gpui::test]
2769    async fn test_tracking_active_path(cx: &mut TestAppContext) {
2770        cx.foreground().forbid_parking();
2771        Settings::test_async(cx);
2772        let fs = FakeFs::new(cx.background());
2773        fs.insert_tree(
2774            "/root1",
2775            json!({
2776                "one.txt": "",
2777                "two.txt": "",
2778            }),
2779        )
2780        .await;
2781        fs.insert_tree(
2782            "/root2",
2783            json!({
2784                "three.txt": "",
2785            }),
2786        )
2787        .await;
2788
2789        let project = Project::test(fs, ["root1".as_ref()], cx).await;
2790        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2791        let worktree_id = project.read_with(cx, |project, cx| {
2792            project.worktrees(cx).next().unwrap().read(cx).id()
2793        });
2794
2795        let item1 = cx.add_view(window_id, |_| {
2796            let mut item = TestItem::new();
2797            item.project_path = Some((worktree_id, "one.txt").into());
2798            item
2799        });
2800        let item2 = cx.add_view(window_id, |_| {
2801            let mut item = TestItem::new();
2802            item.project_path = Some((worktree_id, "two.txt").into());
2803            item
2804        });
2805
2806        // Add an item to an empty pane
2807        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
2808        project.read_with(cx, |project, cx| {
2809            assert_eq!(
2810                project.active_entry(),
2811                project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2812            );
2813        });
2814        assert_eq!(
2815            cx.current_window_title(window_id).as_deref(),
2816            Some("one.txt — root1")
2817        );
2818
2819        // Add a second item to a non-empty pane
2820        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
2821        assert_eq!(
2822            cx.current_window_title(window_id).as_deref(),
2823            Some("two.txt — root1")
2824        );
2825        project.read_with(cx, |project, cx| {
2826            assert_eq!(
2827                project.active_entry(),
2828                project.entry_for_path(&(worktree_id, "two.txt").into(), cx)
2829            );
2830        });
2831
2832        // Close the active item
2833        workspace
2834            .update(cx, |workspace, cx| {
2835                Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
2836            })
2837            .await
2838            .unwrap();
2839        assert_eq!(
2840            cx.current_window_title(window_id).as_deref(),
2841            Some("one.txt — root1")
2842        );
2843        project.read_with(cx, |project, cx| {
2844            assert_eq!(
2845                project.active_entry(),
2846                project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2847            );
2848        });
2849
2850        // Add a project folder
2851        project
2852            .update(cx, |project, cx| {
2853                project.find_or_create_local_worktree("/root2", true, cx)
2854            })
2855            .await
2856            .unwrap();
2857        assert_eq!(
2858            cx.current_window_title(window_id).as_deref(),
2859            Some("one.txt — root1, root2")
2860        );
2861
2862        // Remove a project folder
2863        project.update(cx, |project, cx| {
2864            project.remove_worktree(worktree_id, cx);
2865        });
2866        assert_eq!(
2867            cx.current_window_title(window_id).as_deref(),
2868            Some("one.txt — root2")
2869        );
2870    }
2871
2872    #[gpui::test]
2873    async fn test_close_window(cx: &mut TestAppContext) {
2874        cx.foreground().forbid_parking();
2875        Settings::test_async(cx);
2876        let fs = FakeFs::new(cx.background());
2877        fs.insert_tree("/root", json!({ "one": "" })).await;
2878
2879        let project = Project::test(fs, ["root".as_ref()], cx).await;
2880        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2881
2882        // When there are no dirty items, there's nothing to do.
2883        let item1 = cx.add_view(window_id, |_| TestItem::new());
2884        workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
2885        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2886        assert_eq!(task.await.unwrap(), true);
2887
2888        // When there are dirty untitled items, prompt to save each one. If the user
2889        // cancels any prompt, then abort.
2890        let item2 = cx.add_view(window_id, |_| {
2891            let mut item = TestItem::new();
2892            item.is_dirty = true;
2893            item
2894        });
2895        let item3 = cx.add_view(window_id, |_| {
2896            let mut item = TestItem::new();
2897            item.is_dirty = true;
2898            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2899            item
2900        });
2901        workspace.update(cx, |w, cx| {
2902            w.add_item(Box::new(item2.clone()), cx);
2903            w.add_item(Box::new(item3.clone()), cx);
2904        });
2905        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2906        cx.foreground().run_until_parked();
2907        cx.simulate_prompt_answer(window_id, 2 /* cancel */);
2908        cx.foreground().run_until_parked();
2909        assert!(!cx.has_pending_prompt(window_id));
2910        assert_eq!(task.await.unwrap(), false);
2911    }
2912
2913    #[gpui::test]
2914    async fn test_close_pane_items(cx: &mut TestAppContext) {
2915        cx.foreground().forbid_parking();
2916        Settings::test_async(cx);
2917        let fs = FakeFs::new(cx.background());
2918
2919        let project = Project::test(fs, None, cx).await;
2920        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
2921
2922        let item1 = cx.add_view(window_id, |_| {
2923            let mut item = TestItem::new();
2924            item.is_dirty = true;
2925            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2926            item
2927        });
2928        let item2 = cx.add_view(window_id, |_| {
2929            let mut item = TestItem::new();
2930            item.is_dirty = true;
2931            item.has_conflict = true;
2932            item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
2933            item
2934        });
2935        let item3 = cx.add_view(window_id, |_| {
2936            let mut item = TestItem::new();
2937            item.is_dirty = true;
2938            item.has_conflict = true;
2939            item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
2940            item
2941        });
2942        let item4 = cx.add_view(window_id, |_| {
2943            let mut item = TestItem::new();
2944            item.is_dirty = true;
2945            item
2946        });
2947        let pane = workspace.update(cx, |workspace, cx| {
2948            workspace.add_item(Box::new(item1.clone()), cx);
2949            workspace.add_item(Box::new(item2.clone()), cx);
2950            workspace.add_item(Box::new(item3.clone()), cx);
2951            workspace.add_item(Box::new(item4.clone()), cx);
2952            workspace.active_pane().clone()
2953        });
2954
2955        let close_items = workspace.update(cx, |workspace, cx| {
2956            pane.update(cx, |pane, cx| {
2957                pane.activate_item(1, true, true, false, cx);
2958                assert_eq!(pane.active_item().unwrap().id(), item2.id());
2959            });
2960
2961            let item1_id = item1.id();
2962            let item3_id = item3.id();
2963            let item4_id = item4.id();
2964            Pane::close_items(workspace, pane.clone(), cx, move |id| {
2965                [item1_id, item3_id, item4_id].contains(&id)
2966            })
2967        });
2968
2969        cx.foreground().run_until_parked();
2970        pane.read_with(cx, |pane, _| {
2971            assert_eq!(pane.items().count(), 4);
2972            assert_eq!(pane.active_item().unwrap().id(), item1.id());
2973        });
2974
2975        cx.simulate_prompt_answer(window_id, 0);
2976        cx.foreground().run_until_parked();
2977        pane.read_with(cx, |pane, cx| {
2978            assert_eq!(item1.read(cx).save_count, 1);
2979            assert_eq!(item1.read(cx).save_as_count, 0);
2980            assert_eq!(item1.read(cx).reload_count, 0);
2981            assert_eq!(pane.items().count(), 3);
2982            assert_eq!(pane.active_item().unwrap().id(), item3.id());
2983        });
2984
2985        cx.simulate_prompt_answer(window_id, 1);
2986        cx.foreground().run_until_parked();
2987        pane.read_with(cx, |pane, cx| {
2988            assert_eq!(item3.read(cx).save_count, 0);
2989            assert_eq!(item3.read(cx).save_as_count, 0);
2990            assert_eq!(item3.read(cx).reload_count, 1);
2991            assert_eq!(pane.items().count(), 2);
2992            assert_eq!(pane.active_item().unwrap().id(), item4.id());
2993        });
2994
2995        cx.simulate_prompt_answer(window_id, 0);
2996        cx.foreground().run_until_parked();
2997        cx.simulate_new_path_selection(|_| Some(Default::default()));
2998        close_items.await.unwrap();
2999        pane.read_with(cx, |pane, cx| {
3000            assert_eq!(item4.read(cx).save_count, 0);
3001            assert_eq!(item4.read(cx).save_as_count, 1);
3002            assert_eq!(item4.read(cx).reload_count, 0);
3003            assert_eq!(pane.items().count(), 1);
3004            assert_eq!(pane.active_item().unwrap().id(), item2.id());
3005        });
3006    }
3007
3008    #[gpui::test]
3009    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
3010        cx.foreground().forbid_parking();
3011        Settings::test_async(cx);
3012        let fs = FakeFs::new(cx.background());
3013
3014        let project = Project::test(fs, [], cx).await;
3015        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3016
3017        // Create several workspace items with single project entries, and two
3018        // workspace items with multiple project entries.
3019        let single_entry_items = (0..=4)
3020            .map(|project_entry_id| {
3021                let mut item = TestItem::new();
3022                item.is_dirty = true;
3023                item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
3024                item.is_singleton = true;
3025                item
3026            })
3027            .collect::<Vec<_>>();
3028        let item_2_3 = {
3029            let mut item = TestItem::new();
3030            item.is_dirty = true;
3031            item.is_singleton = false;
3032            item.project_entry_ids =
3033                vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
3034            item
3035        };
3036        let item_3_4 = {
3037            let mut item = TestItem::new();
3038            item.is_dirty = true;
3039            item.is_singleton = false;
3040            item.project_entry_ids =
3041                vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
3042            item
3043        };
3044
3045        // Create two panes that contain the following project entries:
3046        //   left pane:
3047        //     multi-entry items:   (2, 3)
3048        //     single-entry items:  0, 1, 2, 3, 4
3049        //   right pane:
3050        //     single-entry items:  1
3051        //     multi-entry items:   (3, 4)
3052        let left_pane = workspace.update(cx, |workspace, cx| {
3053            let left_pane = workspace.active_pane().clone();
3054            workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
3055            for item in &single_entry_items {
3056                workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
3057            }
3058            left_pane.update(cx, |pane, cx| {
3059                pane.activate_item(2, true, true, false, cx);
3060            });
3061
3062            workspace
3063                .split_pane(left_pane.clone(), SplitDirection::Right, cx)
3064                .unwrap();
3065            workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
3066
3067            left_pane
3068        });
3069
3070        // When closing all of the items in the left pane, we should be prompted twice:
3071        // once for project entry 0, and once for project entry 2. After those two
3072        // prompts, the task should complete.
3073        let close = workspace.update(cx, |workspace, cx| {
3074            workspace.activate_pane(left_pane.clone(), cx);
3075            Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
3076        });
3077
3078        cx.foreground().run_until_parked();
3079        left_pane.read_with(cx, |pane, cx| {
3080            assert_eq!(
3081                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3082                &[ProjectEntryId::from_proto(0)]
3083            );
3084        });
3085        cx.simulate_prompt_answer(window_id, 0);
3086
3087        cx.foreground().run_until_parked();
3088        left_pane.read_with(cx, |pane, cx| {
3089            assert_eq!(
3090                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3091                &[ProjectEntryId::from_proto(2)]
3092            );
3093        });
3094        cx.simulate_prompt_answer(window_id, 0);
3095
3096        cx.foreground().run_until_parked();
3097        close.await.unwrap();
3098        left_pane.read_with(cx, |pane, _| {
3099            assert_eq!(pane.items().count(), 0);
3100        });
3101    }
3102
3103    #[gpui::test]
3104    async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
3105        deterministic.forbid_parking();
3106
3107        Settings::test_async(cx);
3108        let fs = FakeFs::new(cx.background());
3109
3110        let project = Project::test(fs, [], cx).await;
3111        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3112
3113        let item = cx.add_view(window_id, |_| {
3114            let mut item = TestItem::new();
3115            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3116            item
3117        });
3118        let item_id = item.id();
3119        workspace.update(cx, |workspace, cx| {
3120            workspace.add_item(Box::new(item.clone()), cx);
3121        });
3122
3123        // Autosave on window change.
3124        item.update(cx, |item, cx| {
3125            cx.update_global(|settings: &mut Settings, _| {
3126                settings.autosave = Autosave::OnWindowChange;
3127            });
3128            item.is_dirty = true;
3129        });
3130
3131        // Deactivating the window saves the file.
3132        cx.simulate_window_activation(None);
3133        deterministic.run_until_parked();
3134        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
3135
3136        // Autosave on focus change.
3137        item.update(cx, |item, cx| {
3138            cx.focus_self();
3139            cx.update_global(|settings: &mut Settings, _| {
3140                settings.autosave = Autosave::OnFocusChange;
3141            });
3142            item.is_dirty = true;
3143        });
3144
3145        // Blurring the item saves the file.
3146        item.update(cx, |_, cx| cx.blur());
3147        deterministic.run_until_parked();
3148        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
3149
3150        // Deactivating the window still saves the file.
3151        cx.simulate_window_activation(Some(window_id));
3152        item.update(cx, |item, cx| {
3153            cx.focus_self();
3154            item.is_dirty = true;
3155        });
3156        cx.simulate_window_activation(None);
3157
3158        deterministic.run_until_parked();
3159        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3160
3161        // Autosave after delay.
3162        item.update(cx, |item, cx| {
3163            cx.update_global(|settings: &mut Settings, _| {
3164                settings.autosave = Autosave::AfterDelay { milliseconds: 500 };
3165            });
3166            item.is_dirty = true;
3167            cx.emit(TestItemEvent::Edit);
3168        });
3169
3170        // Delay hasn't fully expired, so the file is still dirty and unsaved.
3171        deterministic.advance_clock(Duration::from_millis(250));
3172        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3173
3174        // After delay expires, the file is saved.
3175        deterministic.advance_clock(Duration::from_millis(250));
3176        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
3177
3178        // Autosave on focus change, ensuring closing the tab counts as such.
3179        item.update(cx, |item, cx| {
3180            cx.update_global(|settings: &mut Settings, _| {
3181                settings.autosave = Autosave::OnFocusChange;
3182            });
3183            item.is_dirty = true;
3184        });
3185
3186        workspace
3187            .update(cx, |workspace, cx| {
3188                let pane = workspace.active_pane().clone();
3189                Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3190            })
3191            .await
3192            .unwrap();
3193        assert!(!cx.has_pending_prompt(window_id));
3194        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3195
3196        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
3197        workspace.update(cx, |workspace, cx| {
3198            workspace.add_item(Box::new(item.clone()), cx);
3199        });
3200        item.update(cx, |item, cx| {
3201            item.project_entry_ids = Default::default();
3202            item.is_dirty = true;
3203            cx.blur();
3204        });
3205        deterministic.run_until_parked();
3206        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3207
3208        // Ensure autosave is prevented for deleted files also when closing the buffer.
3209        let _close_items = workspace.update(cx, |workspace, cx| {
3210            let pane = workspace.active_pane().clone();
3211            Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3212        });
3213        deterministic.run_until_parked();
3214        assert!(cx.has_pending_prompt(window_id));
3215        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3216    }
3217
3218    #[gpui::test]
3219    async fn test_pane_navigation(
3220        deterministic: Arc<Deterministic>,
3221        cx: &mut gpui::TestAppContext,
3222    ) {
3223        deterministic.forbid_parking();
3224        Settings::test_async(cx);
3225        let fs = FakeFs::new(cx.background());
3226
3227        let project = Project::test(fs, [], cx).await;
3228        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3229
3230        let item = cx.add_view(window_id, |_| {
3231            let mut item = TestItem::new();
3232            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3233            item
3234        });
3235        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3236        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
3237        let toolbar_notify_count = Rc::new(RefCell::new(0));
3238
3239        workspace.update(cx, |workspace, cx| {
3240            workspace.add_item(Box::new(item.clone()), cx);
3241            let toolbar_notification_count = toolbar_notify_count.clone();
3242            cx.observe(&toolbar, move |_, _, _| {
3243                *toolbar_notification_count.borrow_mut() += 1
3244            })
3245            .detach();
3246        });
3247
3248        pane.read_with(cx, |pane, _| {
3249            assert!(!pane.can_navigate_backward());
3250            assert!(!pane.can_navigate_forward());
3251        });
3252
3253        item.update(cx, |item, cx| {
3254            item.set_state("one".to_string(), cx);
3255        });
3256
3257        // Toolbar must be notified to re-render the navigation buttons
3258        assert_eq!(*toolbar_notify_count.borrow(), 1);
3259
3260        pane.read_with(cx, |pane, _| {
3261            assert!(pane.can_navigate_backward());
3262            assert!(!pane.can_navigate_forward());
3263        });
3264
3265        workspace
3266            .update(cx, |workspace, cx| {
3267                Pane::go_back(workspace, Some(pane.clone()), cx)
3268            })
3269            .await;
3270
3271        assert_eq!(*toolbar_notify_count.borrow(), 3);
3272        pane.read_with(cx, |pane, _| {
3273            assert!(!pane.can_navigate_backward());
3274            assert!(pane.can_navigate_forward());
3275        });
3276    }
3277
3278    struct TestItem {
3279        state: String,
3280        save_count: usize,
3281        save_as_count: usize,
3282        reload_count: usize,
3283        is_dirty: bool,
3284        is_singleton: bool,
3285        has_conflict: bool,
3286        project_entry_ids: Vec<ProjectEntryId>,
3287        project_path: Option<ProjectPath>,
3288        nav_history: Option<ItemNavHistory>,
3289        tab_descriptions: Option<Vec<&'static str>>,
3290        tab_detail: Cell<Option<usize>>,
3291    }
3292
3293    enum TestItemEvent {
3294        Edit,
3295    }
3296
3297    impl Clone for TestItem {
3298        fn clone(&self) -> Self {
3299            Self {
3300                state: self.state.clone(),
3301                save_count: self.save_count,
3302                save_as_count: self.save_as_count,
3303                reload_count: self.reload_count,
3304                is_dirty: self.is_dirty,
3305                is_singleton: self.is_singleton,
3306                has_conflict: self.has_conflict,
3307                project_entry_ids: self.project_entry_ids.clone(),
3308                project_path: self.project_path.clone(),
3309                nav_history: None,
3310                tab_descriptions: None,
3311                tab_detail: Default::default(),
3312            }
3313        }
3314    }
3315
3316    impl TestItem {
3317        fn new() -> Self {
3318            Self {
3319                state: String::new(),
3320                save_count: 0,
3321                save_as_count: 0,
3322                reload_count: 0,
3323                is_dirty: false,
3324                has_conflict: false,
3325                project_entry_ids: Vec::new(),
3326                project_path: None,
3327                is_singleton: true,
3328                nav_history: None,
3329                tab_descriptions: None,
3330                tab_detail: Default::default(),
3331            }
3332        }
3333
3334        fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
3335            self.push_to_nav_history(cx);
3336            self.state = state;
3337        }
3338
3339        fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
3340            if let Some(history) = &mut self.nav_history {
3341                history.push(Some(Box::new(self.state.clone())), cx);
3342            }
3343        }
3344    }
3345
3346    impl Entity for TestItem {
3347        type Event = TestItemEvent;
3348    }
3349
3350    impl View for TestItem {
3351        fn ui_name() -> &'static str {
3352            "TestItem"
3353        }
3354
3355        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3356            Empty::new().boxed()
3357        }
3358    }
3359
3360    impl Item for TestItem {
3361        fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
3362            self.tab_descriptions.as_ref().and_then(|descriptions| {
3363                let description = *descriptions.get(detail).or(descriptions.last())?;
3364                Some(description.into())
3365            })
3366        }
3367
3368        fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {
3369            self.tab_detail.set(detail);
3370            Empty::new().boxed()
3371        }
3372
3373        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
3374            self.project_path.clone()
3375        }
3376
3377        fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
3378            self.project_entry_ids.iter().copied().collect()
3379        }
3380
3381        fn is_singleton(&self, _: &AppContext) -> bool {
3382            self.is_singleton
3383        }
3384
3385        fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
3386            self.nav_history = Some(history);
3387        }
3388
3389        fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
3390            let state = *state.downcast::<String>().unwrap_or_default();
3391            if state != self.state {
3392                self.state = state;
3393                true
3394            } else {
3395                false
3396            }
3397        }
3398
3399        fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
3400            self.push_to_nav_history(cx);
3401        }
3402
3403        fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
3404        where
3405            Self: Sized,
3406        {
3407            Some(self.clone())
3408        }
3409
3410        fn is_dirty(&self, _: &AppContext) -> bool {
3411            self.is_dirty
3412        }
3413
3414        fn has_conflict(&self, _: &AppContext) -> bool {
3415            self.has_conflict
3416        }
3417
3418        fn can_save(&self, _: &AppContext) -> bool {
3419            self.project_entry_ids.len() > 0
3420        }
3421
3422        fn save(
3423            &mut self,
3424            _: ModelHandle<Project>,
3425            _: &mut ViewContext<Self>,
3426        ) -> Task<anyhow::Result<()>> {
3427            self.save_count += 1;
3428            self.is_dirty = false;
3429            Task::ready(Ok(()))
3430        }
3431
3432        fn save_as(
3433            &mut self,
3434            _: ModelHandle<Project>,
3435            _: std::path::PathBuf,
3436            _: &mut ViewContext<Self>,
3437        ) -> Task<anyhow::Result<()>> {
3438            self.save_as_count += 1;
3439            self.is_dirty = false;
3440            Task::ready(Ok(()))
3441        }
3442
3443        fn reload(
3444            &mut self,
3445            _: ModelHandle<Project>,
3446            _: &mut ViewContext<Self>,
3447        ) -> Task<anyhow::Result<()>> {
3448            self.reload_count += 1;
3449            self.is_dirty = false;
3450            Task::ready(Ok(()))
3451        }
3452
3453        fn should_update_tab_on_event(_: &Self::Event) -> bool {
3454            true
3455        }
3456
3457        fn is_edit_event(event: &Self::Event) -> bool {
3458            matches!(event, TestItemEvent::Edit)
3459        }
3460    }
3461}