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