workspace.rs

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