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