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, Contact, PeerId, Subscription, TypedEnvelope, User,
  12    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;
  53
  54type ProjectItemBuilders = HashMap<
  55    TypeId,
  56    fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
  57>;
  58
  59type FollowableItemBuilder = fn(
  60    ViewHandle<Pane>,
  61    ModelHandle<Project>,
  62    &mut Option<proto::view::Variant>,
  63    &mut MutableAppContext,
  64) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
  65type FollowableItemBuilders = HashMap<
  66    TypeId,
  67    (
  68        FollowableItemBuilder,
  69        fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
  70    ),
  71>;
  72
  73actions!(
  74    workspace,
  75    [
  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 contact: Arc<Contact>,
 102    pub project_index: usize,
 103    pub app_state: Arc<AppState>,
 104}
 105
 106impl_internal_actions!(
 107    workspace,
 108    [Open, OpenNew, OpenPaths, ToggleFollow, JoinProject]
 109);
 110
 111pub fn init(client: &Arc<Client>, cx: &mut MutableAppContext) {
 112    pane::init(cx);
 113
 114    cx.add_global_action(open);
 115    cx.add_global_action(move |action: &OpenPaths, cx: &mut MutableAppContext| {
 116        open_paths(&action.paths, &action.app_state, cx).detach();
 117    });
 118    cx.add_global_action(move |action: &OpenNew, cx: &mut MutableAppContext| {
 119        open_new(&action.0, cx)
 120    });
 121    cx.add_global_action(move |action: &JoinProject, cx: &mut MutableAppContext| {
 122        join_project(
 123            action.contact.clone(),
 124            action.project_index,
 125            &action.app_state,
 126            cx,
 127        )
 128        .detach();
 129    });
 130
 131    cx.add_async_action(Workspace::toggle_follow);
 132    cx.add_async_action(Workspace::follow_next_collaborator);
 133    cx.add_action(
 134        |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
 135            let pane = workspace.active_pane().clone();
 136            workspace.unfollow(&pane, cx);
 137        },
 138    );
 139    cx.add_action(
 140        |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
 141            workspace.save_active_item(cx).detach_and_log_err(cx);
 142        },
 143    );
 144    cx.add_action(Workspace::toggle_sidebar_item);
 145    cx.add_action(Workspace::toggle_sidebar_item_focus);
 146    cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
 147        workspace.activate_previous_pane(cx)
 148    });
 149    cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
 150        workspace.activate_next_pane(cx)
 151    });
 152
 153    client.add_view_request_handler(Workspace::handle_follow);
 154    client.add_view_message_handler(Workspace::handle_unfollow);
 155    client.add_view_message_handler(Workspace::handle_update_followers);
 156}
 157
 158pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
 159    cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
 160        builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
 161            let item = model.downcast::<I::Item>().unwrap();
 162            Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
 163        });
 164    });
 165}
 166
 167pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
 168    cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
 169        builders.insert(
 170            TypeId::of::<I>(),
 171            (
 172                |pane, project, state, cx| {
 173                    I::from_state_proto(pane, project, state, cx).map(|task| {
 174                        cx.foreground()
 175                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
 176                    })
 177                },
 178                |this| Box::new(this.downcast::<I>().unwrap()),
 179            ),
 180        );
 181    });
 182}
 183
 184pub struct AppState {
 185    pub languages: Arc<LanguageRegistry>,
 186    pub themes: Arc<ThemeRegistry>,
 187    pub client: Arc<client::Client>,
 188    pub user_store: ModelHandle<client::UserStore>,
 189    pub fs: Arc<dyn fs::Fs>,
 190    pub channel_list: ModelHandle<client::ChannelList>,
 191    pub build_window_options: fn() -> WindowOptions<'static>,
 192    pub build_workspace:
 193        fn(ModelHandle<Project>, &Arc<AppState>, &mut ViewContext<Workspace>) -> 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
 638#[derive(Clone)]
 639pub struct WorkspaceParams {
 640    pub project: ModelHandle<Project>,
 641    pub client: Arc<Client>,
 642    pub fs: Arc<dyn Fs>,
 643    pub languages: Arc<LanguageRegistry>,
 644    pub themes: Arc<ThemeRegistry>,
 645    pub user_store: ModelHandle<UserStore>,
 646    pub channel_list: ModelHandle<ChannelList>,
 647}
 648
 649impl WorkspaceParams {
 650    #[cfg(any(test, feature = "test-support"))]
 651    pub fn test(cx: &mut MutableAppContext) -> Self {
 652        let settings = Settings::test(cx);
 653        cx.set_global(settings);
 654
 655        let fs = project::FakeFs::new(cx.background().clone());
 656        let languages = Arc::new(LanguageRegistry::test());
 657        let http_client = client::test::FakeHttpClient::with_404_response();
 658        let client = Client::new(http_client.clone());
 659        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 660        let project = Project::local(
 661            client.clone(),
 662            user_store.clone(),
 663            languages.clone(),
 664            fs.clone(),
 665            cx,
 666        );
 667        Self {
 668            project,
 669            channel_list: cx
 670                .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
 671            client,
 672            themes: ThemeRegistry::new((), cx.font_cache().clone()),
 673            fs,
 674            languages,
 675            user_store,
 676        }
 677    }
 678
 679    #[cfg(any(test, feature = "test-support"))]
 680    pub fn local(app_state: &Arc<AppState>, cx: &mut MutableAppContext) -> Self {
 681        Self {
 682            project: Project::local(
 683                app_state.client.clone(),
 684                app_state.user_store.clone(),
 685                app_state.languages.clone(),
 686                app_state.fs.clone(),
 687                cx,
 688            ),
 689            client: app_state.client.clone(),
 690            fs: app_state.fs.clone(),
 691            themes: app_state.themes.clone(),
 692            languages: app_state.languages.clone(),
 693            user_store: app_state.user_store.clone(),
 694            channel_list: app_state.channel_list.clone(),
 695        }
 696    }
 697}
 698
 699pub enum Event {
 700    PaneAdded(ViewHandle<Pane>),
 701    ContactRequestedJoin(u64),
 702}
 703
 704pub struct Workspace {
 705    weak_self: WeakViewHandle<Self>,
 706    client: Arc<Client>,
 707    user_store: ModelHandle<client::UserStore>,
 708    remote_entity_subscription: Option<Subscription>,
 709    fs: Arc<dyn Fs>,
 710    themes: Arc<ThemeRegistry>,
 711    modal: Option<AnyViewHandle>,
 712    center: PaneGroup,
 713    left_sidebar: ViewHandle<Sidebar>,
 714    right_sidebar: ViewHandle<Sidebar>,
 715    panes: Vec<ViewHandle<Pane>>,
 716    active_pane: ViewHandle<Pane>,
 717    status_bar: ViewHandle<StatusBar>,
 718    notifications: Vec<Box<dyn NotificationHandle>>,
 719    project: ModelHandle<Project>,
 720    leader_state: LeaderState,
 721    follower_states_by_leader: FollowerStatesByLeader,
 722    last_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,
 723    _observe_current_user: Task<()>,
 724}
 725
 726#[derive(Default)]
 727struct LeaderState {
 728    followers: HashSet<PeerId>,
 729}
 730
 731type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
 732
 733#[derive(Default)]
 734struct FollowerState {
 735    active_view_id: Option<u64>,
 736    items_by_leader_view_id: HashMap<u64, FollowerItem>,
 737}
 738
 739#[derive(Debug)]
 740enum FollowerItem {
 741    Loading(Vec<proto::update_view::Variant>),
 742    Loaded(Box<dyn FollowableItemHandle>),
 743}
 744
 745impl Workspace {
 746    pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
 747        cx.observe(&params.project, |_, project, cx| {
 748            if project.read(cx).is_read_only() {
 749                cx.blur();
 750            }
 751            cx.notify()
 752        })
 753        .detach();
 754
 755        cx.subscribe(&params.project, move |this, project, event, cx| {
 756            match event {
 757                project::Event::RemoteIdChanged(remote_id) => {
 758                    this.project_remote_id_changed(*remote_id, cx);
 759                }
 760                project::Event::CollaboratorLeft(peer_id) => {
 761                    this.collaborator_left(*peer_id, cx);
 762                }
 763                _ => {}
 764            }
 765            if project.read(cx).is_read_only() {
 766                cx.blur();
 767            }
 768            cx.notify()
 769        })
 770        .detach();
 771
 772        let pane = cx.add_view(|cx| Pane::new(cx));
 773        let pane_id = pane.id();
 774        cx.observe(&pane, move |me, _, cx| {
 775            let active_entry = me.active_project_path(cx);
 776            me.project
 777                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 778        })
 779        .detach();
 780        cx.subscribe(&pane, move |me, _, event, cx| {
 781            me.handle_pane_event(pane_id, event, cx)
 782        })
 783        .detach();
 784        cx.focus(&pane);
 785        cx.emit(Event::PaneAdded(pane.clone()));
 786
 787        let mut current_user = params.user_store.read(cx).watch_current_user().clone();
 788        let mut connection_status = params.client.status().clone();
 789        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 790            current_user.recv().await;
 791            connection_status.recv().await;
 792            let mut stream =
 793                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 794
 795            while stream.recv().await.is_some() {
 796                cx.update(|cx| {
 797                    if let Some(this) = this.upgrade(cx) {
 798                        this.update(cx, |_, cx| cx.notify());
 799                    }
 800                })
 801            }
 802        });
 803
 804        let weak_self = cx.weak_handle();
 805
 806        cx.emit_global(WorkspaceCreated(weak_self.clone()));
 807
 808        let left_sidebar = cx.add_view(|_| Sidebar::new(Side::Left));
 809        let right_sidebar = cx.add_view(|_| Sidebar::new(Side::Right));
 810        let left_sidebar_buttons = cx.add_view(|cx| SidebarButtons::new(left_sidebar.clone(), cx));
 811        let right_sidebar_buttons =
 812            cx.add_view(|cx| SidebarButtons::new(right_sidebar.clone(), cx));
 813        let status_bar = cx.add_view(|cx| {
 814            let mut status_bar = StatusBar::new(&pane.clone(), cx);
 815            status_bar.add_left_item(left_sidebar_buttons, cx);
 816            status_bar.add_right_item(right_sidebar_buttons, cx);
 817            status_bar
 818        });
 819
 820        let mut this = Workspace {
 821            modal: None,
 822            weak_self,
 823            center: PaneGroup::new(pane.clone()),
 824            panes: vec![pane.clone()],
 825            active_pane: pane.clone(),
 826            status_bar,
 827            notifications: Default::default(),
 828            client: params.client.clone(),
 829            remote_entity_subscription: None,
 830            user_store: params.user_store.clone(),
 831            fs: params.fs.clone(),
 832            themes: params.themes.clone(),
 833            left_sidebar,
 834            right_sidebar,
 835            project: params.project.clone(),
 836            leader_state: Default::default(),
 837            follower_states_by_leader: Default::default(),
 838            last_leaders_by_pane: Default::default(),
 839            _observe_current_user,
 840        };
 841        this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
 842        this
 843    }
 844
 845    pub fn weak_handle(&self) -> WeakViewHandle<Self> {
 846        self.weak_self.clone()
 847    }
 848
 849    pub fn left_sidebar(&self) -> &ViewHandle<Sidebar> {
 850        &self.left_sidebar
 851    }
 852
 853    pub fn right_sidebar(&self) -> &ViewHandle<Sidebar> {
 854        &self.right_sidebar
 855    }
 856
 857    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
 858        &self.status_bar
 859    }
 860
 861    pub fn user_store(&self) -> &ModelHandle<UserStore> {
 862        &self.user_store
 863    }
 864
 865    pub fn project(&self) -> &ModelHandle<Project> {
 866        &self.project
 867    }
 868
 869    pub fn themes(&self) -> Arc<ThemeRegistry> {
 870        self.themes.clone()
 871    }
 872
 873    pub fn worktrees<'a>(
 874        &self,
 875        cx: &'a AppContext,
 876    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 877        self.project.read(cx).worktrees(cx)
 878    }
 879
 880    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 881        paths.iter().all(|path| self.contains_path(&path, cx))
 882    }
 883
 884    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 885        for worktree in self.worktrees(cx) {
 886            let worktree = worktree.read(cx).as_local();
 887            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 888                return true;
 889            }
 890        }
 891        false
 892    }
 893
 894    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
 895        let futures = self
 896            .worktrees(cx)
 897            .filter_map(|worktree| worktree.read(cx).as_local())
 898            .map(|worktree| worktree.scan_complete())
 899            .collect::<Vec<_>>();
 900        async move {
 901            for future in futures {
 902                future.await;
 903            }
 904        }
 905    }
 906
 907    pub fn open_paths(
 908        &mut self,
 909        mut abs_paths: Vec<PathBuf>,
 910        cx: &mut ViewContext<Self>,
 911    ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
 912        let fs = self.fs.clone();
 913
 914        // Sort the paths to ensure we add worktrees for parents before their children.
 915        abs_paths.sort_unstable();
 916        cx.spawn(|this, mut cx| async move {
 917            let mut entries = Vec::new();
 918            for path in &abs_paths {
 919                entries.push(
 920                    this.update(&mut cx, |this, cx| this.project_path_for_path(path, cx))
 921                        .await
 922                        .ok(),
 923                );
 924            }
 925
 926            let tasks = abs_paths
 927                .iter()
 928                .cloned()
 929                .zip(entries.into_iter())
 930                .map(|(abs_path, project_path)| {
 931                    let this = this.clone();
 932                    cx.spawn(|mut cx| {
 933                        let fs = fs.clone();
 934                        async move {
 935                            let project_path = project_path?;
 936                            if fs.is_file(&abs_path).await {
 937                                Some(
 938                                    this.update(&mut cx, |this, cx| {
 939                                        this.open_path(project_path, true, cx)
 940                                    })
 941                                    .await,
 942                                )
 943                            } else {
 944                                None
 945                            }
 946                        }
 947                    })
 948                })
 949                .collect::<Vec<_>>();
 950
 951            futures::future::join_all(tasks).await
 952        })
 953    }
 954
 955    fn project_path_for_path(
 956        &self,
 957        abs_path: &Path,
 958        cx: &mut ViewContext<Self>,
 959    ) -> Task<Result<ProjectPath>> {
 960        let entry = self.project().update(cx, |project, cx| {
 961            project.find_or_create_local_worktree(abs_path, true, cx)
 962        });
 963        cx.spawn(|_, cx| async move {
 964            let (worktree, path) = entry.await?;
 965            Ok(ProjectPath {
 966                worktree_id: worktree.read_with(&cx, |t, _| t.id()),
 967                path: path.into(),
 968            })
 969        })
 970    }
 971
 972    /// Returns the modal that was toggled closed if it was open.
 973    pub fn toggle_modal<V, F>(
 974        &mut self,
 975        cx: &mut ViewContext<Self>,
 976        add_view: F,
 977    ) -> Option<ViewHandle<V>>
 978    where
 979        V: 'static + View,
 980        F: FnOnce(&mut Self, &mut ViewContext<Self>) -> ViewHandle<V>,
 981    {
 982        cx.notify();
 983        // Whatever modal was visible is getting clobbered. If its the same type as V, then return
 984        // it. Otherwise, create a new modal and set it as active.
 985        let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
 986        if let Some(already_open_modal) = already_open_modal {
 987            cx.focus_self();
 988            Some(already_open_modal)
 989        } else {
 990            let modal = add_view(self, cx);
 991            cx.focus(&modal);
 992            self.modal = Some(modal.into());
 993            None
 994        }
 995    }
 996
 997    pub fn modal(&self) -> Option<&AnyViewHandle> {
 998        self.modal.as_ref()
 999    }
1000
1001    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
1002        if self.modal.take().is_some() {
1003            cx.focus(&self.active_pane);
1004            cx.notify();
1005        }
1006    }
1007
1008    pub fn show_notification<V: Notification>(
1009        &mut self,
1010        notification: ViewHandle<V>,
1011        cx: &mut ViewContext<Self>,
1012    ) {
1013        cx.subscribe(&notification, |this, handle, event, cx| {
1014            if handle.read(cx).should_dismiss_notification_on_event(event) {
1015                this.dismiss_notification(handle.id(), cx);
1016            }
1017        })
1018        .detach();
1019        self.notifications.push(Box::new(notification));
1020        cx.notify();
1021    }
1022
1023    fn dismiss_notification(&mut self, id: usize, cx: &mut ViewContext<Self>) {
1024        self.notifications.retain(|handle| {
1025            if handle.id() == id {
1026                cx.notify();
1027                false
1028            } else {
1029                true
1030            }
1031        });
1032    }
1033
1034    pub fn items<'a>(
1035        &'a self,
1036        cx: &'a AppContext,
1037    ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1038        self.panes.iter().flat_map(|pane| pane.read(cx).items())
1039    }
1040
1041    pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
1042        self.items_of_type(cx).max_by_key(|item| item.id())
1043    }
1044
1045    pub fn items_of_type<'a, T: Item>(
1046        &'a self,
1047        cx: &'a AppContext,
1048    ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
1049        self.panes
1050            .iter()
1051            .flat_map(|pane| pane.read(cx).items_of_type())
1052    }
1053
1054    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1055        self.active_pane().read(cx).active_item()
1056    }
1057
1058    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1059        self.active_item(cx).and_then(|item| item.project_path(cx))
1060    }
1061
1062    pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
1063        let project = self.project.clone();
1064        if let Some(item) = self.active_item(cx) {
1065            if item.can_save(cx) {
1066                if item.has_conflict(cx.as_ref()) {
1067                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1068
1069                    let mut answer = cx.prompt(
1070                        PromptLevel::Warning,
1071                        CONFLICT_MESSAGE,
1072                        &["Overwrite", "Cancel"],
1073                    );
1074                    cx.spawn(|_, mut cx| async move {
1075                        let answer = answer.recv().await;
1076                        if answer == Some(0) {
1077                            cx.update(|cx| item.save(project, cx)).await?;
1078                        }
1079                        Ok(())
1080                    })
1081                } else {
1082                    item.save(project, cx)
1083                }
1084            } else if item.can_save_as(cx) {
1085                let worktree = self.worktrees(cx).next();
1086                let start_abs_path = worktree
1087                    .and_then(|w| w.read(cx).as_local())
1088                    .map_or(Path::new(""), |w| w.abs_path())
1089                    .to_path_buf();
1090                let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1091                cx.spawn(|_, mut cx| async move {
1092                    if let Some(abs_path) = abs_path.recv().await.flatten() {
1093                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1094                    }
1095                    Ok(())
1096                })
1097            } else {
1098                Task::ready(Ok(()))
1099            }
1100        } else {
1101            Task::ready(Ok(()))
1102        }
1103    }
1104
1105    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1106        let sidebar = match action.side {
1107            Side::Left => &mut self.left_sidebar,
1108            Side::Right => &mut self.right_sidebar,
1109        };
1110        let active_item = sidebar.update(cx, |sidebar, cx| {
1111            sidebar.toggle_item(action.item_index, cx);
1112            sidebar.active_item().map(|item| item.to_any())
1113        });
1114        if let Some(active_item) = active_item {
1115            cx.focus(active_item);
1116        } else {
1117            cx.focus_self();
1118        }
1119        cx.notify();
1120    }
1121
1122    pub fn toggle_sidebar_item_focus(
1123        &mut self,
1124        action: &ToggleSidebarItemFocus,
1125        cx: &mut ViewContext<Self>,
1126    ) {
1127        let sidebar = match action.side {
1128            Side::Left => &mut self.left_sidebar,
1129            Side::Right => &mut self.right_sidebar,
1130        };
1131        let active_item = sidebar.update(cx, |sidebar, cx| {
1132            sidebar.activate_item(action.item_index, cx);
1133            sidebar.active_item().cloned()
1134        });
1135        if let Some(active_item) = active_item {
1136            if active_item.is_focused(cx) {
1137                cx.focus_self();
1138            } else {
1139                cx.focus(active_item.to_any());
1140            }
1141        }
1142        cx.notify();
1143    }
1144
1145    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1146        let pane = cx.add_view(|cx| Pane::new(cx));
1147        let pane_id = pane.id();
1148        cx.observe(&pane, move |me, _, cx| {
1149            let active_entry = me.active_project_path(cx);
1150            me.project
1151                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1152        })
1153        .detach();
1154        cx.subscribe(&pane, move |me, _, event, cx| {
1155            me.handle_pane_event(pane_id, event, cx)
1156        })
1157        .detach();
1158        self.panes.push(pane.clone());
1159        self.activate_pane(pane.clone(), cx);
1160        cx.emit(Event::PaneAdded(pane.clone()));
1161        pane
1162    }
1163
1164    pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1165        let pane = self.active_pane().clone();
1166        Pane::add_item(self, pane, item, true, true, cx);
1167    }
1168
1169    pub fn open_path(
1170        &mut self,
1171        path: impl Into<ProjectPath>,
1172        focus_item: bool,
1173        cx: &mut ViewContext<Self>,
1174    ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1175        let pane = self.active_pane().downgrade();
1176        let task = self.load_path(path.into(), cx);
1177        cx.spawn(|this, mut cx| async move {
1178            let (project_entry_id, build_item) = task.await?;
1179            let pane = pane
1180                .upgrade(&cx)
1181                .ok_or_else(|| anyhow!("pane was closed"))?;
1182            this.update(&mut cx, |this, cx| {
1183                Ok(Pane::open_item(
1184                    this,
1185                    pane,
1186                    project_entry_id,
1187                    focus_item,
1188                    cx,
1189                    build_item,
1190                ))
1191            })
1192        })
1193    }
1194
1195    pub(crate) fn load_path(
1196        &mut self,
1197        path: ProjectPath,
1198        cx: &mut ViewContext<Self>,
1199    ) -> Task<
1200        Result<(
1201            ProjectEntryId,
1202            impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1203        )>,
1204    > {
1205        let project = self.project().clone();
1206        let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1207        let window_id = cx.window_id();
1208        cx.as_mut().spawn(|mut cx| async move {
1209            let (project_entry_id, project_item) = project_item.await?;
1210            let build_item = cx.update(|cx| {
1211                cx.default_global::<ProjectItemBuilders>()
1212                    .get(&project_item.model_type())
1213                    .ok_or_else(|| anyhow!("no item builder for project item"))
1214                    .cloned()
1215            })?;
1216            let build_item =
1217                move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1218            Ok((project_entry_id, build_item))
1219        })
1220    }
1221
1222    pub fn open_project_item<T>(
1223        &mut self,
1224        project_item: ModelHandle<T::Item>,
1225        cx: &mut ViewContext<Self>,
1226    ) -> ViewHandle<T>
1227    where
1228        T: ProjectItem,
1229    {
1230        use project::Item as _;
1231
1232        let entry_id = project_item.read(cx).entry_id(cx);
1233        if let Some(item) = entry_id
1234            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1235            .and_then(|item| item.downcast())
1236        {
1237            self.activate_item(&item, cx);
1238            return item;
1239        }
1240
1241        let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1242        self.add_item(Box::new(item.clone()), cx);
1243        item
1244    }
1245
1246    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1247        let result = self.panes.iter().find_map(|pane| {
1248            if let Some(ix) = pane.read(cx).index_for_item(item) {
1249                Some((pane.clone(), ix))
1250            } else {
1251                None
1252            }
1253        });
1254        if let Some((pane, ix)) = result {
1255            self.activate_pane(pane.clone(), cx);
1256            pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, cx));
1257            true
1258        } else {
1259            false
1260        }
1261    }
1262
1263    pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1264        let next_pane = {
1265            let panes = self.center.panes();
1266            let ix = panes
1267                .iter()
1268                .position(|pane| **pane == self.active_pane)
1269                .unwrap();
1270            let next_ix = (ix + 1) % panes.len();
1271            panes[next_ix].clone()
1272        };
1273        self.activate_pane(next_pane, cx);
1274    }
1275
1276    pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1277        let prev_pane = {
1278            let panes = self.center.panes();
1279            let ix = panes
1280                .iter()
1281                .position(|pane| **pane == self.active_pane)
1282                .unwrap();
1283            let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1284            panes[prev_ix].clone()
1285        };
1286        self.activate_pane(prev_pane, cx);
1287    }
1288
1289    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1290        if self.active_pane != pane {
1291            self.active_pane = pane.clone();
1292            self.status_bar.update(cx, |status_bar, cx| {
1293                status_bar.set_active_pane(&self.active_pane, cx);
1294            });
1295            cx.focus(&self.active_pane);
1296            cx.notify();
1297        }
1298
1299        self.update_followers(
1300            proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1301                id: self.active_item(cx).map(|item| item.id() as u64),
1302                leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1303            }),
1304            cx,
1305        );
1306    }
1307
1308    fn handle_pane_event(
1309        &mut self,
1310        pane_id: usize,
1311        event: &pane::Event,
1312        cx: &mut ViewContext<Self>,
1313    ) {
1314        if let Some(pane) = self.pane(pane_id) {
1315            match event {
1316                pane::Event::Split(direction) => {
1317                    self.split_pane(pane, *direction, cx);
1318                }
1319                pane::Event::Remove => {
1320                    self.remove_pane(pane, cx);
1321                }
1322                pane::Event::Activate => {
1323                    self.activate_pane(pane, cx);
1324                }
1325                pane::Event::ActivateItem { local } => {
1326                    if *local {
1327                        self.unfollow(&pane, cx);
1328                    }
1329                }
1330            }
1331        } else {
1332            error!("pane {} not found", pane_id);
1333        }
1334    }
1335
1336    pub fn split_pane(
1337        &mut self,
1338        pane: ViewHandle<Pane>,
1339        direction: SplitDirection,
1340        cx: &mut ViewContext<Self>,
1341    ) -> ViewHandle<Pane> {
1342        let new_pane = self.add_pane(cx);
1343        self.activate_pane(new_pane.clone(), cx);
1344        if let Some(item) = pane.read(cx).active_item() {
1345            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1346                Pane::add_item(self, new_pane.clone(), clone, true, true, cx);
1347            }
1348        }
1349        self.center.split(&pane, &new_pane, direction).unwrap();
1350        cx.notify();
1351        new_pane
1352    }
1353
1354    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1355        if self.center.remove(&pane).unwrap() {
1356            self.panes.retain(|p| p != &pane);
1357            self.activate_pane(self.panes.last().unwrap().clone(), cx);
1358            self.unfollow(&pane, cx);
1359            self.last_leaders_by_pane.remove(&pane.downgrade());
1360            cx.notify();
1361        }
1362    }
1363
1364    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1365        &self.panes
1366    }
1367
1368    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1369        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1370    }
1371
1372    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1373        &self.active_pane
1374    }
1375
1376    fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1377        if let Some(remote_id) = remote_id {
1378            self.remote_entity_subscription =
1379                Some(self.client.add_view_for_remote_entity(remote_id, cx));
1380        } else {
1381            self.remote_entity_subscription.take();
1382        }
1383    }
1384
1385    fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1386        self.leader_state.followers.remove(&peer_id);
1387        if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1388            for state in states_by_pane.into_values() {
1389                for item in state.items_by_leader_view_id.into_values() {
1390                    if let FollowerItem::Loaded(item) = item {
1391                        item.set_leader_replica_id(None, cx);
1392                    }
1393                }
1394            }
1395        }
1396        cx.notify();
1397    }
1398
1399    pub fn toggle_follow(
1400        &mut self,
1401        ToggleFollow(leader_id): &ToggleFollow,
1402        cx: &mut ViewContext<Self>,
1403    ) -> Option<Task<Result<()>>> {
1404        let leader_id = *leader_id;
1405        let pane = self.active_pane().clone();
1406
1407        if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1408            if leader_id == prev_leader_id {
1409                return None;
1410            }
1411        }
1412
1413        self.last_leaders_by_pane
1414            .insert(pane.downgrade(), leader_id);
1415        self.follower_states_by_leader
1416            .entry(leader_id)
1417            .or_default()
1418            .insert(pane.clone(), Default::default());
1419        cx.notify();
1420
1421        let project_id = self.project.read(cx).remote_id()?;
1422        let request = self.client.request(proto::Follow {
1423            project_id,
1424            leader_id: leader_id.0,
1425        });
1426        Some(cx.spawn_weak(|this, mut cx| async move {
1427            let response = request.await?;
1428            if let Some(this) = this.upgrade(&cx) {
1429                this.update(&mut cx, |this, _| {
1430                    let state = this
1431                        .follower_states_by_leader
1432                        .get_mut(&leader_id)
1433                        .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1434                        .ok_or_else(|| anyhow!("following interrupted"))?;
1435                    state.active_view_id = response.active_view_id;
1436                    Ok::<_, anyhow::Error>(())
1437                })?;
1438                Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1439                    .await?;
1440            }
1441            Ok(())
1442        }))
1443    }
1444
1445    pub fn follow_next_collaborator(
1446        &mut self,
1447        _: &FollowNextCollaborator,
1448        cx: &mut ViewContext<Self>,
1449    ) -> Option<Task<Result<()>>> {
1450        let collaborators = self.project.read(cx).collaborators();
1451        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1452            let mut collaborators = collaborators.keys().copied();
1453            while let Some(peer_id) = collaborators.next() {
1454                if peer_id == leader_id {
1455                    break;
1456                }
1457            }
1458            collaborators.next()
1459        } else if let Some(last_leader_id) =
1460            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1461        {
1462            if collaborators.contains_key(last_leader_id) {
1463                Some(*last_leader_id)
1464            } else {
1465                None
1466            }
1467        } else {
1468            None
1469        };
1470
1471        next_leader_id
1472            .or_else(|| collaborators.keys().copied().next())
1473            .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1474    }
1475
1476    pub fn unfollow(
1477        &mut self,
1478        pane: &ViewHandle<Pane>,
1479        cx: &mut ViewContext<Self>,
1480    ) -> Option<PeerId> {
1481        for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1482            let leader_id = *leader_id;
1483            if let Some(state) = states_by_pane.remove(&pane) {
1484                for (_, item) in state.items_by_leader_view_id {
1485                    if let FollowerItem::Loaded(item) = item {
1486                        item.set_leader_replica_id(None, cx);
1487                    }
1488                }
1489
1490                if states_by_pane.is_empty() {
1491                    self.follower_states_by_leader.remove(&leader_id);
1492                    if let Some(project_id) = self.project.read(cx).remote_id() {
1493                        self.client
1494                            .send(proto::Unfollow {
1495                                project_id,
1496                                leader_id: leader_id.0,
1497                            })
1498                            .log_err();
1499                    }
1500                }
1501
1502                cx.notify();
1503                return Some(leader_id);
1504            }
1505        }
1506        None
1507    }
1508
1509    fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1510        let theme = &cx.global::<Settings>().theme;
1511        match &*self.client.status().borrow() {
1512            client::Status::ConnectionError
1513            | client::Status::ConnectionLost
1514            | client::Status::Reauthenticating
1515            | client::Status::Reconnecting { .. }
1516            | client::Status::ReconnectionError { .. } => Some(
1517                Container::new(
1518                    Align::new(
1519                        ConstrainedBox::new(
1520                            Svg::new("icons/offline-14.svg")
1521                                .with_color(theme.workspace.titlebar.offline_icon.color)
1522                                .boxed(),
1523                        )
1524                        .with_width(theme.workspace.titlebar.offline_icon.width)
1525                        .boxed(),
1526                    )
1527                    .boxed(),
1528                )
1529                .with_style(theme.workspace.titlebar.offline_icon.container)
1530                .boxed(),
1531            ),
1532            client::Status::UpgradeRequired => Some(
1533                Label::new(
1534                    "Please update Zed to collaborate".to_string(),
1535                    theme.workspace.titlebar.outdated_warning.text.clone(),
1536                )
1537                .contained()
1538                .with_style(theme.workspace.titlebar.outdated_warning.container)
1539                .aligned()
1540                .boxed(),
1541            ),
1542            _ => None,
1543        }
1544    }
1545
1546    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1547        let mut worktree_root_names = String::new();
1548        {
1549            let mut worktrees = self.project.read(cx).visible_worktrees(cx).peekable();
1550            while let Some(worktree) = worktrees.next() {
1551                worktree_root_names.push_str(worktree.read(cx).root_name());
1552                if worktrees.peek().is_some() {
1553                    worktree_root_names.push_str(", ");
1554                }
1555            }
1556        }
1557
1558        ConstrainedBox::new(
1559            Container::new(
1560                Stack::new()
1561                    .with_child(
1562                        Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
1563                            .aligned()
1564                            .left()
1565                            .boxed(),
1566                    )
1567                    .with_child(
1568                        Align::new(
1569                            Flex::row()
1570                                .with_children(self.render_collaborators(theme, cx))
1571                                .with_children(self.render_current_user(
1572                                    self.user_store.read(cx).current_user().as_ref(),
1573                                    self.project.read(cx).replica_id(),
1574                                    theme,
1575                                    cx,
1576                                ))
1577                                .with_children(self.render_connection_status(cx))
1578                                .boxed(),
1579                        )
1580                        .right()
1581                        .boxed(),
1582                    )
1583                    .boxed(),
1584            )
1585            .with_style(theme.workspace.titlebar.container)
1586            .boxed(),
1587        )
1588        .with_height(theme.workspace.titlebar.height)
1589        .named("titlebar")
1590    }
1591
1592    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1593        let mut collaborators = self
1594            .project
1595            .read(cx)
1596            .collaborators()
1597            .values()
1598            .cloned()
1599            .collect::<Vec<_>>();
1600        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1601        collaborators
1602            .into_iter()
1603            .filter_map(|collaborator| {
1604                Some(self.render_avatar(
1605                    collaborator.user.avatar.clone()?,
1606                    collaborator.replica_id,
1607                    Some(collaborator.peer_id),
1608                    theme,
1609                    cx,
1610                ))
1611            })
1612            .collect()
1613    }
1614
1615    fn render_current_user(
1616        &self,
1617        user: Option<&Arc<User>>,
1618        replica_id: ReplicaId,
1619        theme: &Theme,
1620        cx: &mut RenderContext<Self>,
1621    ) -> Option<ElementBox> {
1622        let status = *self.client.status().borrow();
1623        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1624            Some(self.render_avatar(avatar, replica_id, None, theme, cx))
1625        } else if matches!(status, client::Status::UpgradeRequired) {
1626            None
1627        } else {
1628            Some(
1629                MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1630                    let style = theme
1631                        .workspace
1632                        .titlebar
1633                        .sign_in_prompt
1634                        .style_for(state, false);
1635                    Label::new("Sign in".to_string(), style.text.clone())
1636                        .contained()
1637                        .with_style(style.container)
1638                        .boxed()
1639                })
1640                .on_click(|_, cx| cx.dispatch_action(Authenticate))
1641                .with_cursor_style(CursorStyle::PointingHand)
1642                .aligned()
1643                .boxed(),
1644            )
1645        }
1646    }
1647
1648    fn render_avatar(
1649        &self,
1650        avatar: Arc<ImageData>,
1651        replica_id: ReplicaId,
1652        peer_id: Option<PeerId>,
1653        theme: &Theme,
1654        cx: &mut RenderContext<Self>,
1655    ) -> ElementBox {
1656        let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1657        let is_followed = peer_id.map_or(false, |peer_id| {
1658            self.follower_states_by_leader.contains_key(&peer_id)
1659        });
1660        let mut avatar_style = theme.workspace.titlebar.avatar;
1661        if is_followed {
1662            avatar_style.border = Border::all(1.0, replica_color);
1663        }
1664        let content = Stack::new()
1665            .with_child(
1666                Image::new(avatar)
1667                    .with_style(avatar_style)
1668                    .constrained()
1669                    .with_width(theme.workspace.titlebar.avatar_width)
1670                    .aligned()
1671                    .boxed(),
1672            )
1673            .with_child(
1674                AvatarRibbon::new(replica_color)
1675                    .constrained()
1676                    .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1677                    .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1678                    .aligned()
1679                    .bottom()
1680                    .boxed(),
1681            )
1682            .constrained()
1683            .with_width(theme.workspace.titlebar.avatar_width)
1684            .contained()
1685            .with_margin_left(theme.workspace.titlebar.avatar_margin)
1686            .boxed();
1687
1688        if let Some(peer_id) = peer_id {
1689            MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1690                .with_cursor_style(CursorStyle::PointingHand)
1691                .on_click(move |_, cx| cx.dispatch_action(ToggleFollow(peer_id)))
1692                .boxed()
1693        } else {
1694            content
1695        }
1696    }
1697
1698    fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1699        if self.project.read(cx).is_read_only() {
1700            let theme = &cx.global::<Settings>().theme;
1701            Some(
1702                EventHandler::new(
1703                    Label::new(
1704                        "Your connection to the remote project has been lost.".to_string(),
1705                        theme.workspace.disconnected_overlay.text.clone(),
1706                    )
1707                    .aligned()
1708                    .contained()
1709                    .with_style(theme.workspace.disconnected_overlay.container)
1710                    .boxed(),
1711                )
1712                .capture(|_, _, _| true)
1713                .boxed(),
1714            )
1715        } else {
1716            None
1717        }
1718    }
1719
1720    fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
1721        if self.notifications.is_empty() {
1722            None
1723        } else {
1724            Some(
1725                Flex::column()
1726                    .with_children(self.notifications.iter().map(|notification| {
1727                        ChildView::new(notification.as_ref())
1728                            .contained()
1729                            .with_style(theme.notification)
1730                            .boxed()
1731                    }))
1732                    .constrained()
1733                    .with_width(theme.notifications.width)
1734                    .contained()
1735                    .with_style(theme.notifications.container)
1736                    .aligned()
1737                    .bottom()
1738                    .right()
1739                    .boxed(),
1740            )
1741        }
1742    }
1743
1744    // RPC handlers
1745
1746    async fn handle_follow(
1747        this: ViewHandle<Self>,
1748        envelope: TypedEnvelope<proto::Follow>,
1749        _: Arc<Client>,
1750        mut cx: AsyncAppContext,
1751    ) -> Result<proto::FollowResponse> {
1752        this.update(&mut cx, |this, cx| {
1753            this.leader_state
1754                .followers
1755                .insert(envelope.original_sender_id()?);
1756
1757            let active_view_id = this
1758                .active_item(cx)
1759                .and_then(|i| i.to_followable_item_handle(cx))
1760                .map(|i| i.id() as u64);
1761            Ok(proto::FollowResponse {
1762                active_view_id,
1763                views: this
1764                    .panes()
1765                    .iter()
1766                    .flat_map(|pane| {
1767                        let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1768                        pane.read(cx).items().filter_map({
1769                            let cx = &cx;
1770                            move |item| {
1771                                let id = item.id() as u64;
1772                                let item = item.to_followable_item_handle(cx)?;
1773                                let variant = item.to_state_proto(cx)?;
1774                                Some(proto::View {
1775                                    id,
1776                                    leader_id,
1777                                    variant: Some(variant),
1778                                })
1779                            }
1780                        })
1781                    })
1782                    .collect(),
1783            })
1784        })
1785    }
1786
1787    async fn handle_unfollow(
1788        this: ViewHandle<Self>,
1789        envelope: TypedEnvelope<proto::Unfollow>,
1790        _: Arc<Client>,
1791        mut cx: AsyncAppContext,
1792    ) -> Result<()> {
1793        this.update(&mut cx, |this, _| {
1794            this.leader_state
1795                .followers
1796                .remove(&envelope.original_sender_id()?);
1797            Ok(())
1798        })
1799    }
1800
1801    async fn handle_update_followers(
1802        this: ViewHandle<Self>,
1803        envelope: TypedEnvelope<proto::UpdateFollowers>,
1804        _: Arc<Client>,
1805        mut cx: AsyncAppContext,
1806    ) -> Result<()> {
1807        let leader_id = envelope.original_sender_id()?;
1808        match envelope
1809            .payload
1810            .variant
1811            .ok_or_else(|| anyhow!("invalid update"))?
1812        {
1813            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
1814                this.update(&mut cx, |this, cx| {
1815                    this.update_leader_state(leader_id, cx, |state, _| {
1816                        state.active_view_id = update_active_view.id;
1817                    });
1818                    Ok::<_, anyhow::Error>(())
1819                })
1820            }
1821            proto::update_followers::Variant::UpdateView(update_view) => {
1822                this.update(&mut cx, |this, cx| {
1823                    let variant = update_view
1824                        .variant
1825                        .ok_or_else(|| anyhow!("missing update view variant"))?;
1826                    this.update_leader_state(leader_id, cx, |state, cx| {
1827                        let variant = variant.clone();
1828                        match state
1829                            .items_by_leader_view_id
1830                            .entry(update_view.id)
1831                            .or_insert(FollowerItem::Loading(Vec::new()))
1832                        {
1833                            FollowerItem::Loaded(item) => {
1834                                item.apply_update_proto(variant, cx).log_err();
1835                            }
1836                            FollowerItem::Loading(updates) => updates.push(variant),
1837                        }
1838                    });
1839                    Ok(())
1840                })
1841            }
1842            proto::update_followers::Variant::CreateView(view) => {
1843                let panes = this.read_with(&cx, |this, _| {
1844                    this.follower_states_by_leader
1845                        .get(&leader_id)
1846                        .into_iter()
1847                        .flat_map(|states_by_pane| states_by_pane.keys())
1848                        .cloned()
1849                        .collect()
1850                });
1851                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
1852                    .await?;
1853                Ok(())
1854            }
1855        }
1856        .log_err();
1857
1858        Ok(())
1859    }
1860
1861    async fn add_views_from_leader(
1862        this: ViewHandle<Self>,
1863        leader_id: PeerId,
1864        panes: Vec<ViewHandle<Pane>>,
1865        views: Vec<proto::View>,
1866        cx: &mut AsyncAppContext,
1867    ) -> Result<()> {
1868        let project = this.read_with(cx, |this, _| this.project.clone());
1869        let replica_id = project
1870            .read_with(cx, |project, _| {
1871                project
1872                    .collaborators()
1873                    .get(&leader_id)
1874                    .map(|c| c.replica_id)
1875            })
1876            .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
1877
1878        let item_builders = cx.update(|cx| {
1879            cx.default_global::<FollowableItemBuilders>()
1880                .values()
1881                .map(|b| b.0)
1882                .collect::<Vec<_>>()
1883                .clone()
1884        });
1885
1886        let mut item_tasks_by_pane = HashMap::default();
1887        for pane in panes {
1888            let mut item_tasks = Vec::new();
1889            let mut leader_view_ids = Vec::new();
1890            for view in &views {
1891                let mut variant = view.variant.clone();
1892                if variant.is_none() {
1893                    Err(anyhow!("missing variant"))?;
1894                }
1895                for build_item in &item_builders {
1896                    let task =
1897                        cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
1898                    if let Some(task) = task {
1899                        item_tasks.push(task);
1900                        leader_view_ids.push(view.id);
1901                        break;
1902                    } else {
1903                        assert!(variant.is_some());
1904                    }
1905                }
1906            }
1907
1908            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
1909        }
1910
1911        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
1912            let items = futures::future::try_join_all(item_tasks).await?;
1913            this.update(cx, |this, cx| {
1914                let state = this
1915                    .follower_states_by_leader
1916                    .get_mut(&leader_id)?
1917                    .get_mut(&pane)?;
1918
1919                for (id, item) in leader_view_ids.into_iter().zip(items) {
1920                    item.set_leader_replica_id(Some(replica_id), cx);
1921                    match state.items_by_leader_view_id.entry(id) {
1922                        hash_map::Entry::Occupied(e) => {
1923                            let e = e.into_mut();
1924                            if let FollowerItem::Loading(updates) = e {
1925                                for update in updates.drain(..) {
1926                                    item.apply_update_proto(update, cx)
1927                                        .context("failed to apply view update")
1928                                        .log_err();
1929                                }
1930                            }
1931                            *e = FollowerItem::Loaded(item);
1932                        }
1933                        hash_map::Entry::Vacant(e) => {
1934                            e.insert(FollowerItem::Loaded(item));
1935                        }
1936                    }
1937                }
1938
1939                Some(())
1940            });
1941        }
1942        this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
1943
1944        Ok(())
1945    }
1946
1947    fn update_followers(
1948        &self,
1949        update: proto::update_followers::Variant,
1950        cx: &AppContext,
1951    ) -> Option<()> {
1952        let project_id = self.project.read(cx).remote_id()?;
1953        if !self.leader_state.followers.is_empty() {
1954            self.client
1955                .send(proto::UpdateFollowers {
1956                    project_id,
1957                    follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
1958                    variant: Some(update),
1959                })
1960                .log_err();
1961        }
1962        None
1963    }
1964
1965    pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
1966        self.follower_states_by_leader
1967            .iter()
1968            .find_map(|(leader_id, state)| {
1969                if state.contains_key(pane) {
1970                    Some(*leader_id)
1971                } else {
1972                    None
1973                }
1974            })
1975    }
1976
1977    fn update_leader_state(
1978        &mut self,
1979        leader_id: PeerId,
1980        cx: &mut ViewContext<Self>,
1981        mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
1982    ) {
1983        for (_, state) in self
1984            .follower_states_by_leader
1985            .get_mut(&leader_id)
1986            .into_iter()
1987            .flatten()
1988        {
1989            update_fn(state, cx);
1990        }
1991        self.leader_updated(leader_id, cx);
1992    }
1993
1994    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
1995        let mut items_to_add = Vec::new();
1996        for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
1997            if let Some(active_item) = state
1998                .active_view_id
1999                .and_then(|id| state.items_by_leader_view_id.get(&id))
2000            {
2001                if let FollowerItem::Loaded(item) = active_item {
2002                    items_to_add.push((pane.clone(), item.boxed_clone()));
2003                }
2004            }
2005        }
2006
2007        for (pane, item) in items_to_add {
2008            Pane::add_item(self, pane.clone(), item.boxed_clone(), false, false, cx);
2009            if pane == self.active_pane {
2010                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2011            }
2012            cx.notify();
2013        }
2014        None
2015    }
2016}
2017
2018impl Entity for Workspace {
2019    type Event = Event;
2020}
2021
2022impl View for Workspace {
2023    fn ui_name() -> &'static str {
2024        "Workspace"
2025    }
2026
2027    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2028        let theme = cx.global::<Settings>().theme.clone();
2029        Stack::new()
2030            .with_child(
2031                Flex::column()
2032                    .with_child(self.render_titlebar(&theme, cx))
2033                    .with_child(
2034                        Stack::new()
2035                            .with_child({
2036                                Flex::row()
2037                                    .with_children(
2038                                        if self.left_sidebar.read(cx).active_item().is_some() {
2039                                            Some(
2040                                                ChildView::new(&self.left_sidebar)
2041                                                    .flex(0.8, false)
2042                                                    .boxed(),
2043                                            )
2044                                        } else {
2045                                            None
2046                                        },
2047                                    )
2048                                    .with_child(
2049                                        FlexItem::new(self.center.render(
2050                                            &theme,
2051                                            &self.follower_states_by_leader,
2052                                            self.project.read(cx).collaborators(),
2053                                        ))
2054                                        .flex(1., true)
2055                                        .boxed(),
2056                                    )
2057                                    .with_children(
2058                                        if self.right_sidebar.read(cx).active_item().is_some() {
2059                                            Some(
2060                                                ChildView::new(&self.right_sidebar)
2061                                                    .flex(0.8, false)
2062                                                    .boxed(),
2063                                            )
2064                                        } else {
2065                                            None
2066                                        },
2067                                    )
2068                                    .boxed()
2069                            })
2070                            .with_children(self.modal.as_ref().map(|m| {
2071                                ChildView::new(m)
2072                                    .contained()
2073                                    .with_style(theme.workspace.modal)
2074                                    .aligned()
2075                                    .top()
2076                                    .boxed()
2077                            }))
2078                            .with_children(self.render_notifications(&theme.workspace))
2079                            .flex(1.0, true)
2080                            .boxed(),
2081                    )
2082                    .with_child(ChildView::new(&self.status_bar).boxed())
2083                    .contained()
2084                    .with_background_color(theme.workspace.background)
2085                    .boxed(),
2086            )
2087            .with_children(self.render_disconnected_overlay(cx))
2088            .named("workspace")
2089    }
2090
2091    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2092        cx.focus(&self.active_pane);
2093    }
2094}
2095
2096pub trait WorkspaceHandle {
2097    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2098}
2099
2100impl WorkspaceHandle for ViewHandle<Workspace> {
2101    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2102        self.read(cx)
2103            .worktrees(cx)
2104            .flat_map(|worktree| {
2105                let worktree_id = worktree.read(cx).id();
2106                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2107                    worktree_id,
2108                    path: f.path.clone(),
2109                })
2110            })
2111            .collect::<Vec<_>>()
2112    }
2113}
2114
2115pub struct AvatarRibbon {
2116    color: Color,
2117}
2118
2119impl AvatarRibbon {
2120    pub fn new(color: Color) -> AvatarRibbon {
2121        AvatarRibbon { color }
2122    }
2123}
2124
2125impl Element for AvatarRibbon {
2126    type LayoutState = ();
2127
2128    type PaintState = ();
2129
2130    fn layout(
2131        &mut self,
2132        constraint: gpui::SizeConstraint,
2133        _: &mut gpui::LayoutContext,
2134    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2135        (constraint.max, ())
2136    }
2137
2138    fn paint(
2139        &mut self,
2140        bounds: gpui::geometry::rect::RectF,
2141        _: gpui::geometry::rect::RectF,
2142        _: &mut Self::LayoutState,
2143        cx: &mut gpui::PaintContext,
2144    ) -> Self::PaintState {
2145        let mut path = PathBuilder::new();
2146        path.reset(bounds.lower_left());
2147        path.curve_to(
2148            bounds.origin() + vec2f(bounds.height(), 0.),
2149            bounds.origin(),
2150        );
2151        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2152        path.curve_to(bounds.lower_right(), bounds.upper_right());
2153        path.line_to(bounds.lower_left());
2154        cx.scene.push_path(path.build(self.color, None));
2155    }
2156
2157    fn dispatch_event(
2158        &mut self,
2159        _: &gpui::Event,
2160        _: RectF,
2161        _: RectF,
2162        _: &mut Self::LayoutState,
2163        _: &mut Self::PaintState,
2164        _: &mut gpui::EventContext,
2165    ) -> bool {
2166        false
2167    }
2168
2169    fn debug(
2170        &self,
2171        bounds: gpui::geometry::rect::RectF,
2172        _: &Self::LayoutState,
2173        _: &Self::PaintState,
2174        _: &gpui::DebugContext,
2175    ) -> gpui::json::Value {
2176        json::json!({
2177            "type": "AvatarRibbon",
2178            "bounds": bounds.to_json(),
2179            "color": self.color.to_json(),
2180        })
2181    }
2182}
2183
2184impl std::fmt::Debug for OpenPaths {
2185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2186        f.debug_struct("OpenPaths")
2187            .field("paths", &self.paths)
2188            .finish()
2189    }
2190}
2191
2192fn open(action: &Open, cx: &mut MutableAppContext) {
2193    let app_state = action.0.clone();
2194    let mut paths = cx.prompt_for_paths(PathPromptOptions {
2195        files: true,
2196        directories: true,
2197        multiple: true,
2198    });
2199    cx.spawn(|mut cx| async move {
2200        if let Some(paths) = paths.recv().await.flatten() {
2201            cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths, app_state }));
2202        }
2203    })
2204    .detach();
2205}
2206
2207pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2208
2209pub fn open_paths(
2210    abs_paths: &[PathBuf],
2211    app_state: &Arc<AppState>,
2212    cx: &mut MutableAppContext,
2213) -> Task<(
2214    ViewHandle<Workspace>,
2215    Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2216)> {
2217    log::info!("open paths {:?}", abs_paths);
2218
2219    // Open paths in existing workspace if possible
2220    let mut existing = None;
2221    for window_id in cx.window_ids().collect::<Vec<_>>() {
2222        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2223            if workspace_handle.update(cx, |workspace, cx| {
2224                if workspace.contains_paths(abs_paths, cx.as_ref()) {
2225                    cx.activate_window(window_id);
2226                    existing = Some(workspace_handle.clone());
2227                    true
2228                } else {
2229                    false
2230                }
2231            }) {
2232                break;
2233            }
2234        }
2235    }
2236
2237    let app_state = app_state.clone();
2238    let abs_paths = abs_paths.to_vec();
2239    cx.spawn(|mut cx| async move {
2240        let workspace = if let Some(existing) = existing {
2241            existing
2242        } else {
2243            let contains_directory =
2244                futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2245                    .await
2246                    .contains(&false);
2247
2248            cx.add_window((app_state.build_window_options)(), |cx| {
2249                let project = Project::local(
2250                    app_state.client.clone(),
2251                    app_state.user_store.clone(),
2252                    app_state.languages.clone(),
2253                    app_state.fs.clone(),
2254                    cx,
2255                );
2256                let mut workspace = (app_state.build_workspace)(project, &app_state, cx);
2257                if contains_directory {
2258                    workspace.toggle_sidebar_item(
2259                        &ToggleSidebarItem {
2260                            side: Side::Left,
2261                            item_index: 0,
2262                        },
2263                        cx,
2264                    );
2265                }
2266                workspace
2267            })
2268            .1
2269        };
2270
2271        let items = workspace
2272            .update(&mut cx, |workspace, cx| workspace.open_paths(abs_paths, cx))
2273            .await;
2274        (workspace, items)
2275    })
2276}
2277
2278pub fn join_project(
2279    contact: Arc<Contact>,
2280    project_index: usize,
2281    app_state: &Arc<AppState>,
2282    cx: &mut MutableAppContext,
2283) -> Task<Result<ViewHandle<Workspace>>> {
2284    let project_id = contact.projects[project_index].id;
2285
2286    struct JoiningNotice {
2287        avatar: Option<Arc<ImageData>>,
2288        message: String,
2289    }
2290
2291    impl Entity for JoiningNotice {
2292        type Event = ();
2293    }
2294
2295    impl View for JoiningNotice {
2296        fn ui_name() -> &'static str {
2297            "JoiningProjectWindow"
2298        }
2299
2300        fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2301            let theme = &cx.global::<Settings>().theme.workspace;
2302
2303            Flex::column()
2304                .with_children(self.avatar.clone().map(|avatar| {
2305                    Image::new(avatar)
2306                        .with_style(theme.joining_project_avatar)
2307                        .aligned()
2308                        .boxed()
2309                }))
2310                .with_child(
2311                    Text::new(
2312                        self.message.clone(),
2313                        theme.joining_project_message.text.clone(),
2314                    )
2315                    .contained()
2316                    .with_style(theme.joining_project_message.container)
2317                    .aligned()
2318                    .boxed(),
2319                )
2320                .aligned()
2321                .contained()
2322                .with_background_color(theme.background)
2323                .boxed()
2324        }
2325    }
2326
2327    for window_id in cx.window_ids().collect::<Vec<_>>() {
2328        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2329            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2330                return Task::ready(Ok(workspace));
2331            }
2332        }
2333    }
2334
2335    let app_state = app_state.clone();
2336    cx.spawn(|mut cx| async move {
2337        let (window, joining_notice) = cx.update(|cx| {
2338            cx.add_window((app_state.build_window_options)(), |_| JoiningNotice {
2339                avatar: contact.user.avatar.clone(),
2340                message: format!(
2341                    "Asking to join @{}'s copy of {}...",
2342                    contact.user.github_login,
2343                    humanize_list(&contact.projects[project_index].worktree_root_names)
2344                ),
2345            })
2346        });
2347        let project = Project::remote(
2348            project_id,
2349            app_state.client.clone(),
2350            app_state.user_store.clone(),
2351            app_state.languages.clone(),
2352            app_state.fs.clone(),
2353            &mut cx,
2354        )
2355        .await;
2356
2357        cx.update(|cx| match project {
2358            Ok(project) => Ok(cx.replace_root_view(window, |cx| {
2359                let mut workspace = (app_state.build_workspace)(project, &app_state, cx);
2360                workspace.toggle_sidebar_item(
2361                    &ToggleSidebarItem {
2362                        side: Side::Left,
2363                        item_index: 0,
2364                    },
2365                    cx,
2366                );
2367                workspace
2368            })),
2369            Err(error @ _) => {
2370                let login = &contact.user.github_login;
2371                let message = match error {
2372                    project::JoinProjectError::HostDeclined => {
2373                        format!("@{} declined your request.", login)
2374                    }
2375                    project::JoinProjectError::HostClosedProject => {
2376                        format!(
2377                            "@{} closed their copy of {}.",
2378                            login,
2379                            humanize_list(&contact.projects[project_index].worktree_root_names)
2380                        )
2381                    }
2382                    project::JoinProjectError::HostWentOffline => {
2383                        format!("@{} went offline.", login)
2384                    }
2385                    project::JoinProjectError::Other(_) => "An error occurred.".to_string(),
2386                };
2387                joining_notice.update(cx, |notice, cx| {
2388                    notice.message = message;
2389                    cx.notify();
2390                });
2391
2392                Err(error)?
2393            }
2394        })
2395    })
2396}
2397
2398fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2399    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2400        let project = Project::local(
2401            app_state.client.clone(),
2402            app_state.user_store.clone(),
2403            app_state.languages.clone(),
2404            app_state.fs.clone(),
2405            cx,
2406        );
2407        (app_state.build_workspace)(project, &app_state, cx)
2408    });
2409    cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
2410}
2411
2412fn humanize_list<'a>(items: impl IntoIterator<Item = &'a String>) -> String {
2413    let mut list = String::new();
2414    let mut items = items.into_iter().enumerate().peekable();
2415    while let Some((ix, item)) = items.next() {
2416        if ix > 0 {
2417            list.push_str(", ");
2418        }
2419        if items.peek().is_none() {
2420            list.push_str("and ");
2421        }
2422        list.push_str(item);
2423    }
2424    list
2425}