workspace.rs

   1pub mod lsp_status;
   2pub mod menu;
   3pub mod pane;
   4pub mod pane_group;
   5pub mod settings;
   6pub mod sidebar;
   7mod status_bar;
   8
   9use anyhow::{anyhow, Context, Result};
  10use client::{
  11    proto, Authenticate, ChannelList, Client, PeerId, Subscription, TypedEnvelope, User, UserStore,
  12};
  13use clock::ReplicaId;
  14use collections::{hash_map, HashMap, HashSet};
  15use gpui::{
  16    action,
  17    color::Color,
  18    elements::*,
  19    geometry::{vector::vec2f, PathBuilder},
  20    json::{self, to_string_pretty, ToJson},
  21    keymap::Binding,
  22    platform::{CursorStyle, WindowOptions},
  23    AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, ClipboardItem, Entity,
  24    ImageData, ModelHandle, MutableAppContext, PathPromptOptions, PromptLevel, RenderContext, Task,
  25    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, Worktree};
  33pub use settings::Settings;
  34use sidebar::{Side, Sidebar, SidebarItemId, ToggleSidebarItem, ToggleSidebarItemFocus};
  35use status_bar::StatusBar;
  36pub use status_bar::StatusItemView;
  37use std::{
  38    any::{Any, TypeId},
  39    cell::RefCell,
  40    fmt,
  41    future::Future,
  42    path::{Path, PathBuf},
  43    rc::Rc,
  44    sync::Arc,
  45};
  46use theme::{Theme, ThemeRegistry};
  47use util::ResultExt;
  48
  49type ProjectItemBuilders = HashMap<
  50    TypeId,
  51    fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
  52>;
  53
  54type FollowableItemBuilder = fn(
  55    ViewHandle<Pane>,
  56    ModelHandle<Project>,
  57    &mut Option<proto::view::Variant>,
  58    &mut MutableAppContext,
  59) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
  60type FollowableItemBuilders = HashMap<
  61    TypeId,
  62    (
  63        FollowableItemBuilder,
  64        fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
  65    ),
  66>;
  67
  68action!(Open, Arc<AppState>);
  69action!(OpenNew, Arc<AppState>);
  70action!(OpenPaths, OpenParams);
  71action!(ToggleShare);
  72action!(ToggleFollow, PeerId);
  73action!(Unfollow);
  74action!(JoinProject, JoinProjectParams);
  75action!(Save);
  76action!(DebugElements);
  77
  78pub fn init(client: &Arc<Client>, cx: &mut MutableAppContext) {
  79    pane::init(cx);
  80    menu::init(cx);
  81
  82    cx.add_global_action(open);
  83    cx.add_global_action(move |action: &OpenPaths, cx: &mut MutableAppContext| {
  84        open_paths(&action.0.paths, &action.0.app_state, cx).detach();
  85    });
  86    cx.add_global_action(move |action: &OpenNew, cx: &mut MutableAppContext| {
  87        open_new(&action.0, cx)
  88    });
  89    cx.add_global_action(move |action: &JoinProject, cx: &mut MutableAppContext| {
  90        join_project(action.0.project_id, &action.0.app_state, cx).detach();
  91    });
  92
  93    cx.add_action(Workspace::toggle_share);
  94    cx.add_async_action(Workspace::toggle_follow);
  95    cx.add_action(
  96        |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
  97            let pane = workspace.active_pane().clone();
  98            workspace.unfollow(&pane, cx);
  99        },
 100    );
 101    cx.add_action(
 102        |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
 103            workspace.save_active_item(cx).detach_and_log_err(cx);
 104        },
 105    );
 106    cx.add_action(Workspace::debug_elements);
 107    cx.add_action(Workspace::toggle_sidebar_item);
 108    cx.add_action(Workspace::toggle_sidebar_item_focus);
 109    cx.add_bindings(vec![
 110        Binding::new("cmd-alt-shift-U", Unfollow, None),
 111        Binding::new("cmd-s", Save, None),
 112        Binding::new("cmd-alt-i", DebugElements, None),
 113        Binding::new(
 114            "cmd-shift-!",
 115            ToggleSidebarItem(SidebarItemId {
 116                side: Side::Left,
 117                item_index: 0,
 118            }),
 119            None,
 120        ),
 121        Binding::new(
 122            "cmd-1",
 123            ToggleSidebarItemFocus(SidebarItemId {
 124                side: Side::Left,
 125                item_index: 0,
 126            }),
 127            None,
 128        ),
 129    ]);
 130
 131    client.add_view_request_handler(Workspace::handle_follow);
 132    client.add_view_message_handler(Workspace::handle_unfollow);
 133    client.add_view_message_handler(Workspace::handle_update_followers);
 134}
 135
 136pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
 137    cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
 138        builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
 139            let item = model.downcast::<I::Item>().unwrap();
 140            Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
 141        });
 142    });
 143}
 144
 145pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
 146    cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
 147        builders.insert(
 148            TypeId::of::<I>(),
 149            (
 150                |pane, project, state, cx| {
 151                    I::for_state_message(pane, project, state, cx).map(|task| {
 152                        cx.foreground()
 153                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
 154                    })
 155                },
 156                |this| Box::new(this.downcast::<I>().unwrap()),
 157            ),
 158        );
 159    });
 160}
 161
 162pub struct AppState {
 163    pub languages: Arc<LanguageRegistry>,
 164    pub themes: Arc<ThemeRegistry>,
 165    pub client: Arc<client::Client>,
 166    pub user_store: ModelHandle<client::UserStore>,
 167    pub fs: Arc<dyn fs::Fs>,
 168    pub channel_list: ModelHandle<client::ChannelList>,
 169    pub build_window_options: &'static dyn Fn() -> WindowOptions<'static>,
 170    pub build_workspace: &'static dyn Fn(
 171        ModelHandle<Project>,
 172        &Arc<AppState>,
 173        &mut ViewContext<Workspace>,
 174    ) -> Workspace,
 175}
 176
 177#[derive(Clone)]
 178pub struct OpenParams {
 179    pub paths: Vec<PathBuf>,
 180    pub app_state: Arc<AppState>,
 181}
 182
 183#[derive(Clone)]
 184pub struct JoinProjectParams {
 185    pub project_id: u64,
 186    pub app_state: Arc<AppState>,
 187}
 188
 189pub trait Item: View {
 190    fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
 191    fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) {}
 192    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
 193    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 194    fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
 195    fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
 196    fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
 197    where
 198        Self: Sized,
 199    {
 200        None
 201    }
 202    fn is_dirty(&self, _: &AppContext) -> bool {
 203        false
 204    }
 205    fn has_conflict(&self, _: &AppContext) -> bool {
 206        false
 207    }
 208    fn can_save(&self, cx: &AppContext) -> bool;
 209    fn save(
 210        &mut self,
 211        project: ModelHandle<Project>,
 212        cx: &mut ViewContext<Self>,
 213    ) -> Task<Result<()>>;
 214    fn can_save_as(&self, cx: &AppContext) -> bool;
 215    fn save_as(
 216        &mut self,
 217        project: ModelHandle<Project>,
 218        abs_path: PathBuf,
 219        cx: &mut ViewContext<Self>,
 220    ) -> Task<Result<()>>;
 221    fn should_activate_item_on_event(_: &Self::Event) -> bool {
 222        false
 223    }
 224    fn should_close_item_on_event(_: &Self::Event) -> bool {
 225        false
 226    }
 227    fn should_update_tab_on_event(_: &Self::Event) -> bool {
 228        false
 229    }
 230    fn act_as_type(
 231        &self,
 232        type_id: TypeId,
 233        self_handle: &ViewHandle<Self>,
 234        _: &AppContext,
 235    ) -> Option<AnyViewHandle> {
 236        if TypeId::of::<Self>() == type_id {
 237            Some(self_handle.into())
 238        } else {
 239            None
 240        }
 241    }
 242}
 243
 244pub trait ProjectItem: Item {
 245    type Item: project::Item;
 246
 247    fn for_project_item(
 248        project: ModelHandle<Project>,
 249        item: ModelHandle<Self::Item>,
 250        cx: &mut ViewContext<Self>,
 251    ) -> Self;
 252}
 253
 254pub trait FollowableItem: Item {
 255    fn for_state_message(
 256        pane: ViewHandle<Pane>,
 257        project: ModelHandle<Project>,
 258        state: &mut Option<proto::view::Variant>,
 259        cx: &mut MutableAppContext,
 260    ) -> Option<Task<Result<ViewHandle<Self>>>>;
 261    fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
 262    fn to_state_message(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 263    fn to_update_message(
 264        &self,
 265        event: &Self::Event,
 266        cx: &AppContext,
 267    ) -> Option<proto::update_view::Variant>;
 268    fn apply_update_message(
 269        &mut self,
 270        message: proto::update_view::Variant,
 271        cx: &mut ViewContext<Self>,
 272    ) -> Result<()>;
 273    fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
 274}
 275
 276pub trait FollowableItemHandle: ItemHandle {
 277    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
 278    fn to_state_message(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 279    fn to_update_message(
 280        &self,
 281        event: &dyn Any,
 282        cx: &AppContext,
 283    ) -> Option<proto::update_view::Variant>;
 284    fn apply_update_message(
 285        &self,
 286        message: proto::update_view::Variant,
 287        cx: &mut MutableAppContext,
 288    ) -> Result<()>;
 289    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
 290}
 291
 292impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
 293    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
 294        self.update(cx, |this, cx| {
 295            this.set_leader_replica_id(leader_replica_id, cx)
 296        })
 297    }
 298
 299    fn to_state_message(&self, cx: &AppContext) -> Option<proto::view::Variant> {
 300        self.read(cx).to_state_message(cx)
 301    }
 302
 303    fn to_update_message(
 304        &self,
 305        event: &dyn Any,
 306        cx: &AppContext,
 307    ) -> Option<proto::update_view::Variant> {
 308        self.read(cx).to_update_message(event.downcast_ref()?, cx)
 309    }
 310
 311    fn apply_update_message(
 312        &self,
 313        message: proto::update_view::Variant,
 314        cx: &mut MutableAppContext,
 315    ) -> Result<()> {
 316        self.update(cx, |this, cx| this.apply_update_message(message, cx))
 317    }
 318
 319    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
 320        if let Some(event) = event.downcast_ref() {
 321            T::should_unfollow_on_event(event, cx)
 322        } else {
 323            false
 324        }
 325    }
 326}
 327
 328pub trait ItemHandle: 'static + fmt::Debug {
 329    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
 330    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 331    fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
 332    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 333    fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext);
 334    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
 335    fn added_to_pane(
 336        &self,
 337        workspace: &mut Workspace,
 338        pane: ViewHandle<Pane>,
 339        cx: &mut ViewContext<Workspace>,
 340    );
 341    fn deactivated(&self, cx: &mut MutableAppContext);
 342    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext);
 343    fn id(&self) -> usize;
 344    fn to_any(&self) -> AnyViewHandle;
 345    fn is_dirty(&self, cx: &AppContext) -> bool;
 346    fn has_conflict(&self, cx: &AppContext) -> bool;
 347    fn can_save(&self, cx: &AppContext) -> bool;
 348    fn can_save_as(&self, cx: &AppContext) -> bool;
 349    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
 350    fn save_as(
 351        &self,
 352        project: ModelHandle<Project>,
 353        abs_path: PathBuf,
 354        cx: &mut MutableAppContext,
 355    ) -> Task<Result<()>>;
 356    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
 357    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
 358}
 359
 360pub trait WeakItemHandle {
 361    fn id(&self) -> usize;
 362    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
 363}
 364
 365impl dyn ItemHandle {
 366    pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
 367        self.to_any().downcast()
 368    }
 369
 370    pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
 371        self.act_as_type(TypeId::of::<T>(), cx)
 372            .and_then(|t| t.downcast())
 373    }
 374}
 375
 376impl<T: Item> ItemHandle for ViewHandle<T> {
 377    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
 378        self.read(cx).tab_content(style, cx)
 379    }
 380
 381    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 382        self.read(cx).project_path(cx)
 383    }
 384
 385    fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
 386        self.read(cx).project_entry_id(cx)
 387    }
 388
 389    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 390        Box::new(self.clone())
 391    }
 392
 393    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
 394        self.update(cx, |item, cx| {
 395            cx.add_option_view(|cx| item.clone_on_split(cx))
 396        })
 397        .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 398    }
 399
 400    fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext) {
 401        self.update(cx, |item, cx| {
 402            item.set_nav_history(ItemNavHistory::new(nav_history, &cx.handle()), cx);
 403        })
 404    }
 405
 406    fn added_to_pane(
 407        &self,
 408        workspace: &mut Workspace,
 409        pane: ViewHandle<Pane>,
 410        cx: &mut ViewContext<Workspace>,
 411    ) {
 412        if let Some(followed_item) = self.to_followable_item_handle(cx) {
 413            if let Some(message) = followed_item.to_state_message(cx) {
 414                workspace.update_followers(
 415                    proto::update_followers::Variant::CreateView(proto::View {
 416                        id: followed_item.id() as u64,
 417                        variant: Some(message),
 418                        leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
 419                    }),
 420                    cx,
 421                );
 422            }
 423        }
 424
 425        let pane = pane.downgrade();
 426        cx.subscribe(self, move |workspace, item, event, cx| {
 427            let pane = if let Some(pane) = pane.upgrade(cx) {
 428                pane
 429            } else {
 430                log::error!("unexpected item event after pane was dropped");
 431                return;
 432            };
 433
 434            if let Some(item) = item.to_followable_item_handle(cx) {
 435                if item.should_unfollow_on_event(event, cx) {
 436                    workspace.unfollow(&pane, cx);
 437                }
 438            }
 439
 440            if T::should_close_item_on_event(event) {
 441                pane.update(cx, |pane, cx| pane.close_item(item.id(), cx));
 442                return;
 443            }
 444
 445            if T::should_activate_item_on_event(event) {
 446                pane.update(cx, |pane, cx| {
 447                    if let Some(ix) = pane.index_for_item(&item) {
 448                        pane.activate_item(ix, true, cx);
 449                        pane.activate(cx);
 450                    }
 451                });
 452            }
 453
 454            if T::should_update_tab_on_event(event) {
 455                pane.update(cx, |_, cx| cx.notify());
 456            }
 457
 458            if let Some(message) = item
 459                .to_followable_item_handle(cx)
 460                .and_then(|i| i.to_update_message(event, cx))
 461            {
 462                workspace.update_followers(
 463                    proto::update_followers::Variant::UpdateView(proto::UpdateView {
 464                        id: item.id() as u64,
 465                        variant: Some(message),
 466                        leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
 467                    }),
 468                    cx,
 469                );
 470            }
 471        })
 472        .detach();
 473    }
 474
 475    fn deactivated(&self, cx: &mut MutableAppContext) {
 476        self.update(cx, |this, cx| this.deactivated(cx));
 477    }
 478
 479    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) {
 480        self.update(cx, |this, cx| this.navigate(data, cx));
 481    }
 482
 483    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
 484        self.update(cx, |item, cx| item.save(project, cx))
 485    }
 486
 487    fn save_as(
 488        &self,
 489        project: ModelHandle<Project>,
 490        abs_path: PathBuf,
 491        cx: &mut MutableAppContext,
 492    ) -> Task<anyhow::Result<()>> {
 493        self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
 494    }
 495
 496    fn is_dirty(&self, cx: &AppContext) -> bool {
 497        self.read(cx).is_dirty(cx)
 498    }
 499
 500    fn has_conflict(&self, cx: &AppContext) -> bool {
 501        self.read(cx).has_conflict(cx)
 502    }
 503
 504    fn id(&self) -> usize {
 505        self.id()
 506    }
 507
 508    fn to_any(&self) -> AnyViewHandle {
 509        self.into()
 510    }
 511
 512    fn can_save(&self, cx: &AppContext) -> bool {
 513        self.read(cx).can_save(cx)
 514    }
 515
 516    fn can_save_as(&self, cx: &AppContext) -> bool {
 517        self.read(cx).can_save_as(cx)
 518    }
 519
 520    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
 521        self.read(cx).act_as_type(type_id, self, cx)
 522    }
 523
 524    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 525        if cx.has_global::<FollowableItemBuilders>() {
 526            let builders = cx.global::<FollowableItemBuilders>();
 527            let item = self.to_any();
 528            Some(builders.get(&item.view_type())?.1(item))
 529        } else {
 530            None
 531        }
 532    }
 533}
 534
 535impl Into<AnyViewHandle> for Box<dyn ItemHandle> {
 536    fn into(self) -> AnyViewHandle {
 537        self.to_any()
 538    }
 539}
 540
 541impl Clone for Box<dyn ItemHandle> {
 542    fn clone(&self) -> Box<dyn ItemHandle> {
 543        self.boxed_clone()
 544    }
 545}
 546
 547impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
 548    fn id(&self) -> usize {
 549        self.id()
 550    }
 551
 552    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 553        self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
 554    }
 555}
 556
 557#[derive(Clone)]
 558pub struct WorkspaceParams {
 559    pub project: ModelHandle<Project>,
 560    pub client: Arc<Client>,
 561    pub fs: Arc<dyn Fs>,
 562    pub languages: Arc<LanguageRegistry>,
 563    pub user_store: ModelHandle<UserStore>,
 564    pub channel_list: ModelHandle<ChannelList>,
 565}
 566
 567impl WorkspaceParams {
 568    #[cfg(any(test, feature = "test-support"))]
 569    pub fn test(cx: &mut MutableAppContext) -> Self {
 570        let settings = Settings::test(cx);
 571        cx.set_global(settings);
 572
 573        let fs = project::FakeFs::new(cx.background().clone());
 574        let languages = Arc::new(LanguageRegistry::test());
 575        let http_client = client::test::FakeHttpClient::new(|_| async move {
 576            Ok(client::http::ServerResponse::new(404))
 577        });
 578        let client = Client::new(http_client.clone());
 579        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 580        let project = Project::local(
 581            client.clone(),
 582            user_store.clone(),
 583            languages.clone(),
 584            fs.clone(),
 585            cx,
 586        );
 587        Self {
 588            project,
 589            channel_list: cx
 590                .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
 591            client,
 592            fs,
 593            languages,
 594            user_store,
 595        }
 596    }
 597
 598    #[cfg(any(test, feature = "test-support"))]
 599    pub fn local(app_state: &Arc<AppState>, cx: &mut MutableAppContext) -> Self {
 600        Self {
 601            project: Project::local(
 602                app_state.client.clone(),
 603                app_state.user_store.clone(),
 604                app_state.languages.clone(),
 605                app_state.fs.clone(),
 606                cx,
 607            ),
 608            client: app_state.client.clone(),
 609            fs: app_state.fs.clone(),
 610            languages: app_state.languages.clone(),
 611            user_store: app_state.user_store.clone(),
 612            channel_list: app_state.channel_list.clone(),
 613        }
 614    }
 615}
 616
 617pub struct Workspace {
 618    weak_self: WeakViewHandle<Self>,
 619    client: Arc<Client>,
 620    user_store: ModelHandle<client::UserStore>,
 621    remote_entity_subscription: Option<Subscription>,
 622    fs: Arc<dyn Fs>,
 623    modal: Option<AnyViewHandle>,
 624    center: PaneGroup,
 625    left_sidebar: Sidebar,
 626    right_sidebar: Sidebar,
 627    panes: Vec<ViewHandle<Pane>>,
 628    active_pane: ViewHandle<Pane>,
 629    status_bar: ViewHandle<StatusBar>,
 630    project: ModelHandle<Project>,
 631    leader_state: LeaderState,
 632    follower_states_by_leader: FollowerStatesByLeader,
 633    _observe_current_user: Task<()>,
 634}
 635
 636#[derive(Default)]
 637struct LeaderState {
 638    followers: HashSet<PeerId>,
 639}
 640
 641type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
 642
 643#[derive(Default)]
 644struct FollowerState {
 645    active_view_id: Option<u64>,
 646    items_by_leader_view_id: HashMap<u64, FollowerItem>,
 647}
 648
 649#[derive(Debug)]
 650enum FollowerItem {
 651    Loading(Vec<proto::update_view::Variant>),
 652    Loaded(Box<dyn FollowableItemHandle>),
 653}
 654
 655impl Workspace {
 656    pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
 657        cx.observe(&params.project, |_, project, cx| {
 658            if project.read(cx).is_read_only() {
 659                cx.blur();
 660            }
 661            cx.notify()
 662        })
 663        .detach();
 664
 665        cx.subscribe(&params.project, move |this, project, event, cx| {
 666            if let project::Event::RemoteIdChanged(remote_id) = event {
 667                this.project_remote_id_changed(*remote_id, cx);
 668            }
 669            if project.read(cx).is_read_only() {
 670                cx.blur();
 671            }
 672            cx.notify()
 673        })
 674        .detach();
 675
 676        let pane = cx.add_view(|_| Pane::new());
 677        let pane_id = pane.id();
 678        cx.observe(&pane, move |me, _, cx| {
 679            let active_entry = me.active_project_path(cx);
 680            me.project
 681                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 682        })
 683        .detach();
 684        cx.subscribe(&pane, move |me, _, event, cx| {
 685            me.handle_pane_event(pane_id, event, cx)
 686        })
 687        .detach();
 688        cx.focus(&pane);
 689
 690        let status_bar = cx.add_view(|cx| StatusBar::new(&pane, cx));
 691        let mut current_user = params.user_store.read(cx).watch_current_user().clone();
 692        let mut connection_status = params.client.status().clone();
 693        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 694            current_user.recv().await;
 695            connection_status.recv().await;
 696            let mut stream =
 697                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 698
 699            while stream.recv().await.is_some() {
 700                cx.update(|cx| {
 701                    if let Some(this) = this.upgrade(cx) {
 702                        this.update(cx, |_, cx| cx.notify());
 703                    }
 704                })
 705            }
 706        });
 707
 708        let weak_self = cx.weak_handle();
 709
 710        cx.emit_global(WorkspaceCreated(weak_self.clone()));
 711
 712        let mut this = Workspace {
 713            modal: None,
 714            weak_self,
 715            center: PaneGroup::new(pane.clone()),
 716            panes: vec![pane.clone()],
 717            active_pane: pane.clone(),
 718            status_bar,
 719            client: params.client.clone(),
 720            remote_entity_subscription: None,
 721            user_store: params.user_store.clone(),
 722            fs: params.fs.clone(),
 723            left_sidebar: Sidebar::new(Side::Left),
 724            right_sidebar: Sidebar::new(Side::Right),
 725            project: params.project.clone(),
 726            leader_state: Default::default(),
 727            follower_states_by_leader: Default::default(),
 728            _observe_current_user,
 729        };
 730        this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
 731        this
 732    }
 733
 734    pub fn weak_handle(&self) -> WeakViewHandle<Self> {
 735        self.weak_self.clone()
 736    }
 737
 738    pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
 739        &mut self.left_sidebar
 740    }
 741
 742    pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
 743        &mut self.right_sidebar
 744    }
 745
 746    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
 747        &self.status_bar
 748    }
 749
 750    pub fn project(&self) -> &ModelHandle<Project> {
 751        &self.project
 752    }
 753
 754    pub fn worktrees<'a>(
 755        &self,
 756        cx: &'a AppContext,
 757    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 758        self.project.read(cx).worktrees(cx)
 759    }
 760
 761    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 762        paths.iter().all(|path| self.contains_path(&path, cx))
 763    }
 764
 765    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 766        for worktree in self.worktrees(cx) {
 767            let worktree = worktree.read(cx).as_local();
 768            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 769                return true;
 770            }
 771        }
 772        false
 773    }
 774
 775    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
 776        let futures = self
 777            .worktrees(cx)
 778            .filter_map(|worktree| worktree.read(cx).as_local())
 779            .map(|worktree| worktree.scan_complete())
 780            .collect::<Vec<_>>();
 781        async move {
 782            for future in futures {
 783                future.await;
 784            }
 785        }
 786    }
 787
 788    pub fn open_paths(
 789        &mut self,
 790        abs_paths: &[PathBuf],
 791        cx: &mut ViewContext<Self>,
 792    ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
 793        let entries = abs_paths
 794            .iter()
 795            .cloned()
 796            .map(|path| self.project_path_for_path(&path, cx))
 797            .collect::<Vec<_>>();
 798
 799        let fs = self.fs.clone();
 800        let tasks = abs_paths
 801            .iter()
 802            .cloned()
 803            .zip(entries.into_iter())
 804            .map(|(abs_path, project_path)| {
 805                cx.spawn(|this, mut cx| {
 806                    let fs = fs.clone();
 807                    async move {
 808                        let project_path = project_path.await.ok()?;
 809                        if fs.is_file(&abs_path).await {
 810                            Some(
 811                                this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
 812                                    .await,
 813                            )
 814                        } else {
 815                            None
 816                        }
 817                    }
 818                })
 819            })
 820            .collect::<Vec<_>>();
 821
 822        cx.foreground().spawn(async move {
 823            let mut items = Vec::new();
 824            for task in tasks {
 825                items.push(task.await);
 826            }
 827            items
 828        })
 829    }
 830
 831    fn project_path_for_path(
 832        &self,
 833        abs_path: &Path,
 834        cx: &mut ViewContext<Self>,
 835    ) -> Task<Result<ProjectPath>> {
 836        let entry = self.project().update(cx, |project, cx| {
 837            project.find_or_create_local_worktree(abs_path, true, cx)
 838        });
 839        cx.spawn(|_, cx| async move {
 840            let (worktree, path) = entry.await?;
 841            Ok(ProjectPath {
 842                worktree_id: worktree.read_with(&cx, |t, _| t.id()),
 843                path: path.into(),
 844            })
 845        })
 846    }
 847
 848    // Returns the model that was toggled closed if it was open
 849    pub fn toggle_modal<V, F>(
 850        &mut self,
 851        cx: &mut ViewContext<Self>,
 852        add_view: F,
 853    ) -> Option<ViewHandle<V>>
 854    where
 855        V: 'static + View,
 856        F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
 857    {
 858        cx.notify();
 859        // Whatever modal was visible is getting clobbered. If its the same type as V, then return
 860        // it. Otherwise, create a new modal and set it as active.
 861        let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
 862        if let Some(already_open_modal) = already_open_modal {
 863            cx.focus_self();
 864            Some(already_open_modal)
 865        } else {
 866            let modal = add_view(cx, self);
 867            cx.focus(&modal);
 868            self.modal = Some(modal.into());
 869            None
 870        }
 871    }
 872
 873    pub fn modal(&self) -> Option<&AnyViewHandle> {
 874        self.modal.as_ref()
 875    }
 876
 877    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
 878        if self.modal.take().is_some() {
 879            cx.focus(&self.active_pane);
 880            cx.notify();
 881        }
 882    }
 883
 884    pub fn items<'a>(
 885        &'a self,
 886        cx: &'a AppContext,
 887    ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
 888        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 889    }
 890
 891    pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
 892        self.items_of_type(cx).max_by_key(|item| item.id())
 893    }
 894
 895    pub fn items_of_type<'a, T: Item>(
 896        &'a self,
 897        cx: &'a AppContext,
 898    ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
 899        self.panes
 900            .iter()
 901            .flat_map(|pane| pane.read(cx).items_of_type())
 902    }
 903
 904    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 905        self.active_pane().read(cx).active_item()
 906    }
 907
 908    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
 909        self.active_item(cx).and_then(|item| item.project_path(cx))
 910    }
 911
 912    pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 913        let project = self.project.clone();
 914        if let Some(item) = self.active_item(cx) {
 915            if item.can_save(cx) {
 916                if item.has_conflict(cx.as_ref()) {
 917                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 918
 919                    let mut answer = cx.prompt(
 920                        PromptLevel::Warning,
 921                        CONFLICT_MESSAGE,
 922                        &["Overwrite", "Cancel"],
 923                    );
 924                    cx.spawn(|_, mut cx| async move {
 925                        let answer = answer.recv().await;
 926                        if answer == Some(0) {
 927                            cx.update(|cx| item.save(project, cx)).await?;
 928                        }
 929                        Ok(())
 930                    })
 931                } else {
 932                    item.save(project, cx)
 933                }
 934            } else if item.can_save_as(cx) {
 935                let worktree = self.worktrees(cx).next();
 936                let start_abs_path = worktree
 937                    .and_then(|w| w.read(cx).as_local())
 938                    .map_or(Path::new(""), |w| w.abs_path())
 939                    .to_path_buf();
 940                let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
 941                cx.spawn(|_, mut cx| async move {
 942                    if let Some(abs_path) = abs_path.recv().await.flatten() {
 943                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
 944                    }
 945                    Ok(())
 946                })
 947            } else {
 948                Task::ready(Ok(()))
 949            }
 950        } else {
 951            Task::ready(Ok(()))
 952        }
 953    }
 954
 955    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
 956        let sidebar = match action.0.side {
 957            Side::Left => &mut self.left_sidebar,
 958            Side::Right => &mut self.right_sidebar,
 959        };
 960        sidebar.toggle_item(action.0.item_index);
 961        if let Some(active_item) = sidebar.active_item() {
 962            cx.focus(active_item);
 963        } else {
 964            cx.focus_self();
 965        }
 966        cx.notify();
 967    }
 968
 969    pub fn toggle_sidebar_item_focus(
 970        &mut self,
 971        action: &ToggleSidebarItemFocus,
 972        cx: &mut ViewContext<Self>,
 973    ) {
 974        let sidebar = match action.0.side {
 975            Side::Left => &mut self.left_sidebar,
 976            Side::Right => &mut self.right_sidebar,
 977        };
 978        sidebar.activate_item(action.0.item_index);
 979        if let Some(active_item) = sidebar.active_item() {
 980            if active_item.is_focused(cx) {
 981                cx.focus_self();
 982            } else {
 983                cx.focus(active_item);
 984            }
 985        }
 986        cx.notify();
 987    }
 988
 989    pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
 990        match to_string_pretty(&cx.debug_elements()) {
 991            Ok(json) => {
 992                let kib = json.len() as f32 / 1024.;
 993                cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
 994                log::info!(
 995                    "copied {:.1} KiB of element debug JSON to the clipboard",
 996                    kib
 997                );
 998            }
 999            Err(error) => {
1000                log::error!("error debugging elements: {}", error);
1001            }
1002        };
1003    }
1004
1005    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1006        let pane = cx.add_view(|_| Pane::new());
1007        let pane_id = pane.id();
1008        cx.observe(&pane, move |me, _, cx| {
1009            let active_entry = me.active_project_path(cx);
1010            me.project
1011                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1012        })
1013        .detach();
1014        cx.subscribe(&pane, move |me, _, event, cx| {
1015            me.handle_pane_event(pane_id, event, cx)
1016        })
1017        .detach();
1018        self.panes.push(pane.clone());
1019        self.activate_pane(pane.clone(), cx);
1020        pane
1021    }
1022
1023    pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1024        let pane = self.active_pane().clone();
1025        Pane::add_item(self, pane, item, true, cx);
1026    }
1027
1028    pub fn open_path(
1029        &mut self,
1030        path: impl Into<ProjectPath>,
1031        cx: &mut ViewContext<Self>,
1032    ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1033        let pane = self.active_pane().downgrade();
1034        let task = self.load_path(path.into(), cx);
1035        cx.spawn(|this, mut cx| async move {
1036            let (project_entry_id, build_item) = task.await?;
1037            let pane = pane
1038                .upgrade(&cx)
1039                .ok_or_else(|| anyhow!("pane was closed"))?;
1040            this.update(&mut cx, |this, cx| {
1041                Ok(Pane::open_item(
1042                    this,
1043                    pane,
1044                    project_entry_id,
1045                    cx,
1046                    build_item,
1047                ))
1048            })
1049        })
1050    }
1051
1052    pub(crate) fn load_path(
1053        &mut self,
1054        path: ProjectPath,
1055        cx: &mut ViewContext<Self>,
1056    ) -> Task<
1057        Result<(
1058            ProjectEntryId,
1059            impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1060        )>,
1061    > {
1062        let project = self.project().clone();
1063        let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1064        let window_id = cx.window_id();
1065        cx.as_mut().spawn(|mut cx| async move {
1066            let (project_entry_id, project_item) = project_item.await?;
1067            let build_item = cx.update(|cx| {
1068                cx.default_global::<ProjectItemBuilders>()
1069                    .get(&project_item.model_type())
1070                    .ok_or_else(|| anyhow!("no item builder for project item"))
1071                    .cloned()
1072            })?;
1073            let build_item =
1074                move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1075            Ok((project_entry_id, build_item))
1076        })
1077    }
1078
1079    pub fn open_project_item<T>(
1080        &mut self,
1081        project_item: ModelHandle<T::Item>,
1082        cx: &mut ViewContext<Self>,
1083    ) -> ViewHandle<T>
1084    where
1085        T: ProjectItem,
1086    {
1087        use project::Item as _;
1088
1089        if let Some(item) = project_item
1090            .read(cx)
1091            .entry_id(cx)
1092            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1093            .and_then(|item| item.downcast())
1094        {
1095            self.activate_item(&item, cx);
1096            return item;
1097        }
1098
1099        let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1100        self.add_item(Box::new(item.clone()), cx);
1101        item
1102    }
1103
1104    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1105        let result = self.panes.iter().find_map(|pane| {
1106            if let Some(ix) = pane.read(cx).index_for_item(item) {
1107                Some((pane.clone(), ix))
1108            } else {
1109                None
1110            }
1111        });
1112        if let Some((pane, ix)) = result {
1113            self.activate_pane(pane.clone(), cx);
1114            pane.update(cx, |pane, cx| pane.activate_item(ix, true, cx));
1115            true
1116        } else {
1117            false
1118        }
1119    }
1120
1121    pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1122        let ix = self
1123            .panes
1124            .iter()
1125            .position(|pane| pane == &self.active_pane)
1126            .unwrap();
1127        let next_ix = (ix + 1) % self.panes.len();
1128        self.activate_pane(self.panes[next_ix].clone(), cx);
1129    }
1130
1131    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1132        if self.active_pane != pane {
1133            self.active_pane = pane.clone();
1134            self.status_bar.update(cx, |status_bar, cx| {
1135                status_bar.set_active_pane(&self.active_pane, cx);
1136            });
1137            cx.focus(&self.active_pane);
1138            cx.notify();
1139        }
1140
1141        self.update_followers(
1142            proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1143                id: self.active_item(cx).map(|item| item.id() as u64),
1144                leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1145            }),
1146            cx,
1147        );
1148    }
1149
1150    fn handle_pane_event(
1151        &mut self,
1152        pane_id: usize,
1153        event: &pane::Event,
1154        cx: &mut ViewContext<Self>,
1155    ) {
1156        if let Some(pane) = self.pane(pane_id) {
1157            match event {
1158                pane::Event::Split(direction) => {
1159                    self.split_pane(pane, *direction, cx);
1160                }
1161                pane::Event::Remove => {
1162                    self.remove_pane(pane, cx);
1163                }
1164                pane::Event::Activate => {
1165                    self.activate_pane(pane, cx);
1166                }
1167                pane::Event::ActivateItem { local } => {
1168                    if *local {
1169                        self.unfollow(&pane, cx);
1170                    }
1171                }
1172            }
1173        } else {
1174            error!("pane {} not found", pane_id);
1175        }
1176    }
1177
1178    pub fn split_pane(
1179        &mut self,
1180        pane: ViewHandle<Pane>,
1181        direction: SplitDirection,
1182        cx: &mut ViewContext<Self>,
1183    ) -> ViewHandle<Pane> {
1184        let new_pane = self.add_pane(cx);
1185        self.activate_pane(new_pane.clone(), cx);
1186        if let Some(item) = pane.read(cx).active_item() {
1187            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1188                Pane::add_item(self, new_pane.clone(), clone, true, cx);
1189            }
1190        }
1191        self.center.split(&pane, &new_pane, direction).unwrap();
1192        cx.notify();
1193        new_pane
1194    }
1195
1196    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1197        if self.center.remove(&pane).unwrap() {
1198            self.panes.retain(|p| p != &pane);
1199            self.activate_pane(self.panes.last().unwrap().clone(), cx);
1200            self.unfollow(&pane, cx);
1201            cx.notify();
1202        }
1203    }
1204
1205    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1206        &self.panes
1207    }
1208
1209    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1210        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1211    }
1212
1213    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1214        &self.active_pane
1215    }
1216
1217    fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1218        self.project.update(cx, |project, cx| {
1219            if project.is_local() {
1220                if project.is_shared() {
1221                    project.unshare(cx).detach();
1222                } else {
1223                    project.share(cx).detach();
1224                }
1225            }
1226        });
1227    }
1228
1229    fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1230        if let Some(remote_id) = remote_id {
1231            self.remote_entity_subscription =
1232                Some(self.client.add_view_for_remote_entity(remote_id, cx));
1233        } else {
1234            self.remote_entity_subscription.take();
1235        }
1236    }
1237
1238    pub fn toggle_follow(
1239        &mut self,
1240        ToggleFollow(leader_id): &ToggleFollow,
1241        cx: &mut ViewContext<Self>,
1242    ) -> Option<Task<Result<()>>> {
1243        let leader_id = *leader_id;
1244        let pane = self.active_pane().clone();
1245
1246        if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1247            if leader_id == prev_leader_id {
1248                cx.notify();
1249                return None;
1250            }
1251        }
1252
1253        self.follower_states_by_leader
1254            .entry(leader_id)
1255            .or_default()
1256            .insert(pane.clone(), Default::default());
1257
1258        let project_id = self.project.read(cx).remote_id()?;
1259        let request = self.client.request(proto::Follow {
1260            project_id,
1261            leader_id: leader_id.0,
1262        });
1263        Some(cx.spawn_weak(|this, mut cx| async move {
1264            let response = request.await?;
1265            if let Some(this) = this.upgrade(&cx) {
1266                this.update(&mut cx, |this, _| {
1267                    let state = this
1268                        .follower_states_by_leader
1269                        .get_mut(&leader_id)
1270                        .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1271                        .ok_or_else(|| anyhow!("following interrupted"))?;
1272                    state.active_view_id = response.active_view_id;
1273                    Ok::<_, anyhow::Error>(())
1274                })?;
1275                Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1276                    .await?;
1277            }
1278            Ok(())
1279        }))
1280    }
1281
1282    pub fn unfollow(
1283        &mut self,
1284        pane: &ViewHandle<Pane>,
1285        cx: &mut ViewContext<Self>,
1286    ) -> Option<PeerId> {
1287        for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1288            let leader_id = *leader_id;
1289            if let Some(state) = states_by_pane.remove(&pane) {
1290                for (_, item) in state.items_by_leader_view_id {
1291                    if let FollowerItem::Loaded(item) = item {
1292                        item.set_leader_replica_id(None, cx);
1293                    }
1294                }
1295
1296                if states_by_pane.is_empty() {
1297                    self.follower_states_by_leader.remove(&leader_id);
1298                    if let Some(project_id) = self.project.read(cx).remote_id() {
1299                        self.client
1300                            .send(proto::Unfollow {
1301                                project_id,
1302                                leader_id: leader_id.0,
1303                            })
1304                            .log_err();
1305                    }
1306                }
1307
1308                cx.notify();
1309                return Some(leader_id);
1310            }
1311        }
1312        None
1313    }
1314
1315    fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1316        let theme = &cx.global::<Settings>().theme;
1317        match &*self.client.status().borrow() {
1318            client::Status::ConnectionError
1319            | client::Status::ConnectionLost
1320            | client::Status::Reauthenticating
1321            | client::Status::Reconnecting { .. }
1322            | client::Status::ReconnectionError { .. } => Some(
1323                Container::new(
1324                    Align::new(
1325                        ConstrainedBox::new(
1326                            Svg::new("icons/offline-14.svg")
1327                                .with_color(theme.workspace.titlebar.offline_icon.color)
1328                                .boxed(),
1329                        )
1330                        .with_width(theme.workspace.titlebar.offline_icon.width)
1331                        .boxed(),
1332                    )
1333                    .boxed(),
1334                )
1335                .with_style(theme.workspace.titlebar.offline_icon.container)
1336                .boxed(),
1337            ),
1338            client::Status::UpgradeRequired => Some(
1339                Label::new(
1340                    "Please update Zed to collaborate".to_string(),
1341                    theme.workspace.titlebar.outdated_warning.text.clone(),
1342                )
1343                .contained()
1344                .with_style(theme.workspace.titlebar.outdated_warning.container)
1345                .aligned()
1346                .boxed(),
1347            ),
1348            _ => None,
1349        }
1350    }
1351
1352    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1353        ConstrainedBox::new(
1354            Container::new(
1355                Stack::new()
1356                    .with_child(
1357                        Align::new(
1358                            Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1359                                .boxed(),
1360                        )
1361                        .boxed(),
1362                    )
1363                    .with_child(
1364                        Align::new(
1365                            Flex::row()
1366                                .with_children(self.render_share_icon(theme, cx))
1367                                .with_children(self.render_collaborators(theme, cx))
1368                                .with_child(self.render_current_user(
1369                                    self.user_store.read(cx).current_user().as_ref(),
1370                                    self.project.read(cx).replica_id(),
1371                                    theme,
1372                                    cx,
1373                                ))
1374                                .with_children(self.render_connection_status(cx))
1375                                .boxed(),
1376                        )
1377                        .right()
1378                        .boxed(),
1379                    )
1380                    .boxed(),
1381            )
1382            .with_style(theme.workspace.titlebar.container)
1383            .boxed(),
1384        )
1385        .with_height(theme.workspace.titlebar.height)
1386        .named("titlebar")
1387    }
1388
1389    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1390        let mut collaborators = self
1391            .project
1392            .read(cx)
1393            .collaborators()
1394            .values()
1395            .cloned()
1396            .collect::<Vec<_>>();
1397        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1398        collaborators
1399            .into_iter()
1400            .filter_map(|collaborator| {
1401                Some(self.render_avatar(
1402                    collaborator.user.avatar.clone()?,
1403                    collaborator.replica_id,
1404                    Some(collaborator.peer_id),
1405                    theme,
1406                    cx,
1407                ))
1408            })
1409            .collect()
1410    }
1411
1412    fn render_current_user(
1413        &self,
1414        user: Option<&Arc<User>>,
1415        replica_id: ReplicaId,
1416        theme: &Theme,
1417        cx: &mut RenderContext<Self>,
1418    ) -> ElementBox {
1419        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1420            self.render_avatar(avatar, replica_id, None, theme, cx)
1421        } else {
1422            MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1423                let style = if state.hovered {
1424                    &theme.workspace.titlebar.hovered_sign_in_prompt
1425                } else {
1426                    &theme.workspace.titlebar.sign_in_prompt
1427                };
1428                Label::new("Sign in".to_string(), style.text.clone())
1429                    .contained()
1430                    .with_style(style.container)
1431                    .boxed()
1432            })
1433            .on_click(|cx| cx.dispatch_action(Authenticate))
1434            .with_cursor_style(CursorStyle::PointingHand)
1435            .aligned()
1436            .boxed()
1437        }
1438    }
1439
1440    fn render_avatar(
1441        &self,
1442        avatar: Arc<ImageData>,
1443        replica_id: ReplicaId,
1444        peer_id: Option<PeerId>,
1445        theme: &Theme,
1446        cx: &mut RenderContext<Self>,
1447    ) -> ElementBox {
1448        let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1449        let is_followed = peer_id.map_or(false, |peer_id| {
1450            self.follower_states_by_leader.contains_key(&peer_id)
1451        });
1452        let mut avatar_style = theme.workspace.titlebar.avatar;
1453        if is_followed {
1454            avatar_style.border = Border::all(1.0, replica_color);
1455        }
1456        let content = Stack::new()
1457            .with_child(
1458                Image::new(avatar)
1459                    .with_style(avatar_style)
1460                    .constrained()
1461                    .with_width(theme.workspace.titlebar.avatar_width)
1462                    .aligned()
1463                    .boxed(),
1464            )
1465            .with_child(
1466                AvatarRibbon::new(replica_color)
1467                    .constrained()
1468                    .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1469                    .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1470                    .aligned()
1471                    .bottom()
1472                    .boxed(),
1473            )
1474            .constrained()
1475            .with_width(theme.workspace.right_sidebar.width)
1476            .boxed();
1477
1478        if let Some(peer_id) = peer_id {
1479            MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1480                .with_cursor_style(CursorStyle::PointingHand)
1481                .on_click(move |cx| cx.dispatch_action(ToggleFollow(peer_id)))
1482                .boxed()
1483        } else {
1484            content
1485        }
1486    }
1487
1488    fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1489        if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1490            let color = if self.project().read(cx).is_shared() {
1491                theme.workspace.titlebar.share_icon_active_color
1492            } else {
1493                theme.workspace.titlebar.share_icon_color
1494            };
1495            Some(
1496                MouseEventHandler::new::<ToggleShare, _, _>(0, cx, |_, _| {
1497                    Align::new(
1498                        Svg::new("icons/broadcast-24.svg")
1499                            .with_color(color)
1500                            .constrained()
1501                            .with_width(24.)
1502                            .boxed(),
1503                    )
1504                    .boxed()
1505                })
1506                .with_cursor_style(CursorStyle::PointingHand)
1507                .on_click(|cx| cx.dispatch_action(ToggleShare))
1508                .boxed(),
1509            )
1510        } else {
1511            None
1512        }
1513    }
1514
1515    fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1516        if self.project.read(cx).is_read_only() {
1517            let theme = &cx.global::<Settings>().theme;
1518            Some(
1519                EventHandler::new(
1520                    Label::new(
1521                        "Your connection to the remote project has been lost.".to_string(),
1522                        theme.workspace.disconnected_overlay.text.clone(),
1523                    )
1524                    .aligned()
1525                    .contained()
1526                    .with_style(theme.workspace.disconnected_overlay.container)
1527                    .boxed(),
1528                )
1529                .capture(|_, _, _| true)
1530                .boxed(),
1531            )
1532        } else {
1533            None
1534        }
1535    }
1536
1537    // RPC handlers
1538
1539    async fn handle_follow(
1540        this: ViewHandle<Self>,
1541        envelope: TypedEnvelope<proto::Follow>,
1542        _: Arc<Client>,
1543        mut cx: AsyncAppContext,
1544    ) -> Result<proto::FollowResponse> {
1545        this.update(&mut cx, |this, cx| {
1546            this.leader_state
1547                .followers
1548                .insert(envelope.original_sender_id()?);
1549
1550            let active_view_id = this
1551                .active_item(cx)
1552                .and_then(|i| i.to_followable_item_handle(cx))
1553                .map(|i| i.id() as u64);
1554            Ok(proto::FollowResponse {
1555                active_view_id,
1556                views: this
1557                    .panes()
1558                    .iter()
1559                    .flat_map(|pane| {
1560                        let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1561                        pane.read(cx).items().filter_map({
1562                            let cx = &cx;
1563                            move |item| {
1564                                let id = item.id() as u64;
1565                                let item = item.to_followable_item_handle(cx)?;
1566                                let variant = item.to_state_message(cx)?;
1567                                Some(proto::View {
1568                                    id,
1569                                    leader_id,
1570                                    variant: Some(variant),
1571                                })
1572                            }
1573                        })
1574                    })
1575                    .collect(),
1576            })
1577        })
1578    }
1579
1580    async fn handle_unfollow(
1581        this: ViewHandle<Self>,
1582        envelope: TypedEnvelope<proto::Unfollow>,
1583        _: Arc<Client>,
1584        mut cx: AsyncAppContext,
1585    ) -> Result<()> {
1586        this.update(&mut cx, |this, _| {
1587            this.leader_state
1588                .followers
1589                .remove(&envelope.original_sender_id()?);
1590            Ok(())
1591        })
1592    }
1593
1594    async fn handle_update_followers(
1595        this: ViewHandle<Self>,
1596        envelope: TypedEnvelope<proto::UpdateFollowers>,
1597        _: Arc<Client>,
1598        mut cx: AsyncAppContext,
1599    ) -> Result<()> {
1600        let leader_id = envelope.original_sender_id()?;
1601        match envelope
1602            .payload
1603            .variant
1604            .ok_or_else(|| anyhow!("invalid update"))?
1605        {
1606            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
1607                this.update(&mut cx, |this, cx| {
1608                    this.update_leader_state(leader_id, cx, |state, _| {
1609                        state.active_view_id = update_active_view.id;
1610                    });
1611                    Ok::<_, anyhow::Error>(())
1612                })
1613            }
1614            proto::update_followers::Variant::UpdateView(update_view) => {
1615                this.update(&mut cx, |this, cx| {
1616                    let variant = update_view
1617                        .variant
1618                        .ok_or_else(|| anyhow!("missing update view variant"))?;
1619                    this.update_leader_state(leader_id, cx, |state, cx| {
1620                        let variant = variant.clone();
1621                        match state
1622                            .items_by_leader_view_id
1623                            .entry(update_view.id)
1624                            .or_insert(FollowerItem::Loading(Vec::new()))
1625                        {
1626                            FollowerItem::Loaded(item) => {
1627                                item.apply_update_message(variant, cx).log_err();
1628                            }
1629                            FollowerItem::Loading(updates) => updates.push(variant),
1630                        }
1631                    });
1632                    Ok(())
1633                })
1634            }
1635            proto::update_followers::Variant::CreateView(view) => {
1636                let panes = this.read_with(&cx, |this, _| {
1637                    this.follower_states_by_leader
1638                        .get(&leader_id)
1639                        .into_iter()
1640                        .flat_map(|states_by_pane| states_by_pane.keys())
1641                        .cloned()
1642                        .collect()
1643                });
1644                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
1645                    .await?;
1646                Ok(())
1647            }
1648        }
1649        .log_err();
1650
1651        Ok(())
1652    }
1653
1654    async fn add_views_from_leader(
1655        this: ViewHandle<Self>,
1656        leader_id: PeerId,
1657        panes: Vec<ViewHandle<Pane>>,
1658        views: Vec<proto::View>,
1659        cx: &mut AsyncAppContext,
1660    ) -> Result<()> {
1661        let project = this.read_with(cx, |this, _| this.project.clone());
1662        let replica_id = project
1663            .read_with(cx, |project, _| {
1664                project
1665                    .collaborators()
1666                    .get(&leader_id)
1667                    .map(|c| c.replica_id)
1668            })
1669            .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
1670
1671        let item_builders = cx.update(|cx| {
1672            cx.default_global::<FollowableItemBuilders>()
1673                .values()
1674                .map(|b| b.0)
1675                .collect::<Vec<_>>()
1676                .clone()
1677        });
1678
1679        let mut item_tasks_by_pane = HashMap::default();
1680        for pane in panes {
1681            let mut item_tasks = Vec::new();
1682            let mut leader_view_ids = Vec::new();
1683            for view in &views {
1684                let mut variant = view.variant.clone();
1685                if variant.is_none() {
1686                    Err(anyhow!("missing variant"))?;
1687                }
1688                for build_item in &item_builders {
1689                    let task =
1690                        cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
1691                    if let Some(task) = task {
1692                        item_tasks.push(task);
1693                        leader_view_ids.push(view.id);
1694                        break;
1695                    } else {
1696                        assert!(variant.is_some());
1697                    }
1698                }
1699            }
1700
1701            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
1702        }
1703
1704        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
1705            let items = futures::future::try_join_all(item_tasks).await?;
1706            this.update(cx, |this, cx| {
1707                let state = this
1708                    .follower_states_by_leader
1709                    .get_mut(&leader_id)?
1710                    .get_mut(&pane)?;
1711
1712                for (id, item) in leader_view_ids.into_iter().zip(items) {
1713                    item.set_leader_replica_id(Some(replica_id), cx);
1714                    match state.items_by_leader_view_id.entry(id) {
1715                        hash_map::Entry::Occupied(e) => {
1716                            let e = e.into_mut();
1717                            if let FollowerItem::Loading(updates) = e {
1718                                for update in updates.drain(..) {
1719                                    item.apply_update_message(update, cx)
1720                                        .context("failed to apply view update")
1721                                        .log_err();
1722                                }
1723                            }
1724                            *e = FollowerItem::Loaded(item);
1725                        }
1726                        hash_map::Entry::Vacant(e) => {
1727                            e.insert(FollowerItem::Loaded(item));
1728                        }
1729                    }
1730                }
1731
1732                Some(())
1733            });
1734        }
1735        this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
1736
1737        Ok(())
1738    }
1739
1740    fn update_followers(
1741        &self,
1742        update: proto::update_followers::Variant,
1743        cx: &AppContext,
1744    ) -> Option<()> {
1745        let project_id = self.project.read(cx).remote_id()?;
1746        if !self.leader_state.followers.is_empty() {
1747            self.client
1748                .send(proto::UpdateFollowers {
1749                    project_id,
1750                    follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
1751                    variant: Some(update),
1752                })
1753                .log_err();
1754        }
1755        None
1756    }
1757
1758    pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
1759        self.follower_states_by_leader
1760            .iter()
1761            .find_map(|(leader_id, state)| {
1762                if state.contains_key(pane) {
1763                    Some(*leader_id)
1764                } else {
1765                    None
1766                }
1767            })
1768    }
1769
1770    fn update_leader_state(
1771        &mut self,
1772        leader_id: PeerId,
1773        cx: &mut ViewContext<Self>,
1774        mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
1775    ) {
1776        for (_, state) in self
1777            .follower_states_by_leader
1778            .get_mut(&leader_id)
1779            .into_iter()
1780            .flatten()
1781        {
1782            update_fn(state, cx);
1783        }
1784        self.leader_updated(leader_id, cx);
1785    }
1786
1787    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
1788        let mut items_to_add = Vec::new();
1789        for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
1790            if let Some(active_item) = state
1791                .active_view_id
1792                .and_then(|id| state.items_by_leader_view_id.get(&id))
1793            {
1794                if let FollowerItem::Loaded(item) = active_item {
1795                    items_to_add.push((pane.clone(), item.boxed_clone()));
1796                }
1797            }
1798        }
1799
1800        for (pane, item) in items_to_add {
1801            Pane::add_item(self, pane.clone(), item.boxed_clone(), false, cx);
1802            cx.notify();
1803        }
1804        None
1805    }
1806}
1807
1808impl Entity for Workspace {
1809    type Event = ();
1810}
1811
1812impl View for Workspace {
1813    fn ui_name() -> &'static str {
1814        "Workspace"
1815    }
1816
1817    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1818        let theme = cx.global::<Settings>().theme.clone();
1819        Stack::new()
1820            .with_child(
1821                Flex::column()
1822                    .with_child(self.render_titlebar(&theme, cx))
1823                    .with_child(
1824                        Stack::new()
1825                            .with_child({
1826                                let mut content = Flex::row();
1827                                content.add_child(self.left_sidebar.render(&theme, cx));
1828                                if let Some(element) =
1829                                    self.left_sidebar.render_active_item(&theme, cx)
1830                                {
1831                                    content.add_child(Flexible::new(0.8, false, element).boxed());
1832                                }
1833                                content.add_child(
1834                                    Flex::column()
1835                                        .with_child(
1836                                            Flexible::new(
1837                                                1.,
1838                                                true,
1839                                                self.center.render(
1840                                                    &theme,
1841                                                    &self.follower_states_by_leader,
1842                                                    self.project.read(cx).collaborators(),
1843                                                ),
1844                                            )
1845                                            .boxed(),
1846                                        )
1847                                        .with_child(ChildView::new(&self.status_bar).boxed())
1848                                        .flexible(1., true)
1849                                        .boxed(),
1850                                );
1851                                if let Some(element) =
1852                                    self.right_sidebar.render_active_item(&theme, cx)
1853                                {
1854                                    content.add_child(Flexible::new(0.8, false, element).boxed());
1855                                }
1856                                content.add_child(self.right_sidebar.render(&theme, cx));
1857                                content.boxed()
1858                            })
1859                            .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1860                            .flexible(1.0, true)
1861                            .boxed(),
1862                    )
1863                    .contained()
1864                    .with_background_color(theme.workspace.background)
1865                    .boxed(),
1866            )
1867            .with_children(self.render_disconnected_overlay(cx))
1868            .named("workspace")
1869    }
1870
1871    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1872        cx.focus(&self.active_pane);
1873    }
1874}
1875
1876pub trait WorkspaceHandle {
1877    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1878}
1879
1880impl WorkspaceHandle for ViewHandle<Workspace> {
1881    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1882        self.read(cx)
1883            .worktrees(cx)
1884            .flat_map(|worktree| {
1885                let worktree_id = worktree.read(cx).id();
1886                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1887                    worktree_id,
1888                    path: f.path.clone(),
1889                })
1890            })
1891            .collect::<Vec<_>>()
1892    }
1893}
1894
1895pub struct AvatarRibbon {
1896    color: Color,
1897}
1898
1899impl AvatarRibbon {
1900    pub fn new(color: Color) -> AvatarRibbon {
1901        AvatarRibbon { color }
1902    }
1903}
1904
1905impl Element for AvatarRibbon {
1906    type LayoutState = ();
1907
1908    type PaintState = ();
1909
1910    fn layout(
1911        &mut self,
1912        constraint: gpui::SizeConstraint,
1913        _: &mut gpui::LayoutContext,
1914    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1915        (constraint.max, ())
1916    }
1917
1918    fn paint(
1919        &mut self,
1920        bounds: gpui::geometry::rect::RectF,
1921        _: gpui::geometry::rect::RectF,
1922        _: &mut Self::LayoutState,
1923        cx: &mut gpui::PaintContext,
1924    ) -> Self::PaintState {
1925        let mut path = PathBuilder::new();
1926        path.reset(bounds.lower_left());
1927        path.curve_to(
1928            bounds.origin() + vec2f(bounds.height(), 0.),
1929            bounds.origin(),
1930        );
1931        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1932        path.curve_to(bounds.lower_right(), bounds.upper_right());
1933        path.line_to(bounds.lower_left());
1934        cx.scene.push_path(path.build(self.color, None));
1935    }
1936
1937    fn dispatch_event(
1938        &mut self,
1939        _: &gpui::Event,
1940        _: gpui::geometry::rect::RectF,
1941        _: &mut Self::LayoutState,
1942        _: &mut Self::PaintState,
1943        _: &mut gpui::EventContext,
1944    ) -> bool {
1945        false
1946    }
1947
1948    fn debug(
1949        &self,
1950        bounds: gpui::geometry::rect::RectF,
1951        _: &Self::LayoutState,
1952        _: &Self::PaintState,
1953        _: &gpui::DebugContext,
1954    ) -> gpui::json::Value {
1955        json::json!({
1956            "type": "AvatarRibbon",
1957            "bounds": bounds.to_json(),
1958            "color": self.color.to_json(),
1959        })
1960    }
1961}
1962
1963impl std::fmt::Debug for OpenParams {
1964    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1965        f.debug_struct("OpenParams")
1966            .field("paths", &self.paths)
1967            .finish()
1968    }
1969}
1970
1971fn open(action: &Open, cx: &mut MutableAppContext) {
1972    let app_state = action.0.clone();
1973    let mut paths = cx.prompt_for_paths(PathPromptOptions {
1974        files: true,
1975        directories: true,
1976        multiple: true,
1977    });
1978    cx.spawn(|mut cx| async move {
1979        if let Some(paths) = paths.recv().await.flatten() {
1980            cx.update(|cx| cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state })));
1981        }
1982    })
1983    .detach();
1984}
1985
1986pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
1987
1988pub fn open_paths(
1989    abs_paths: &[PathBuf],
1990    app_state: &Arc<AppState>,
1991    cx: &mut MutableAppContext,
1992) -> Task<ViewHandle<Workspace>> {
1993    log::info!("open paths {:?}", abs_paths);
1994
1995    // Open paths in existing workspace if possible
1996    let mut existing = None;
1997    for window_id in cx.window_ids().collect::<Vec<_>>() {
1998        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
1999            if workspace_handle.update(cx, |workspace, cx| {
2000                if workspace.contains_paths(abs_paths, cx.as_ref()) {
2001                    cx.activate_window(window_id);
2002                    existing = Some(workspace_handle.clone());
2003                    true
2004                } else {
2005                    false
2006                }
2007            }) {
2008                break;
2009            }
2010        }
2011    }
2012
2013    let workspace = existing.unwrap_or_else(|| {
2014        cx.add_window((app_state.build_window_options)(), |cx| {
2015            let project = Project::local(
2016                app_state.client.clone(),
2017                app_state.user_store.clone(),
2018                app_state.languages.clone(),
2019                app_state.fs.clone(),
2020                cx,
2021            );
2022            (app_state.build_workspace)(project, &app_state, cx)
2023        })
2024        .1
2025    });
2026
2027    let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
2028    cx.spawn(|_| async move {
2029        task.await;
2030        workspace
2031    })
2032}
2033
2034pub fn join_project(
2035    project_id: u64,
2036    app_state: &Arc<AppState>,
2037    cx: &mut MutableAppContext,
2038) -> Task<Result<ViewHandle<Workspace>>> {
2039    for window_id in cx.window_ids().collect::<Vec<_>>() {
2040        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2041            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2042                return Task::ready(Ok(workspace));
2043            }
2044        }
2045    }
2046
2047    let app_state = app_state.clone();
2048    cx.spawn(|mut cx| async move {
2049        let project = Project::remote(
2050            project_id,
2051            app_state.client.clone(),
2052            app_state.user_store.clone(),
2053            app_state.languages.clone(),
2054            app_state.fs.clone(),
2055            &mut cx,
2056        )
2057        .await?;
2058        Ok(cx.update(|cx| {
2059            cx.add_window((app_state.build_window_options)(), |cx| {
2060                (app_state.build_workspace)(project, &app_state, cx)
2061            })
2062            .1
2063        }))
2064    })
2065}
2066
2067fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2068    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2069        let project = Project::local(
2070            app_state.client.clone(),
2071            app_state.user_store.clone(),
2072            app_state.languages.clone(),
2073            app_state.fs.clone(),
2074            cx,
2075        );
2076        (app_state.build_workspace)(project, &app_state, cx)
2077    });
2078    cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
2079}