workspace.rs

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