workspace.rs

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