workspace.rs

   1pub mod pane;
   2pub mod pane_group;
   3pub mod sidebar;
   4mod status_bar;
   5mod toolbar;
   6mod waiting_room;
   7
   8use anyhow::{anyhow, Context, Result};
   9use client::{
  10    proto, Authenticate, Client, Contact, PeerId, Subscription, TypedEnvelope, User, UserStore,
  11};
  12use clock::ReplicaId;
  13use collections::{hash_map, HashMap, HashSet};
  14use gpui::{
  15    actions,
  16    color::Color,
  17    elements::*,
  18    geometry::{rect::RectF, vector::vec2f, PathBuilder},
  19    impl_actions, impl_internal_actions,
  20    json::{self, ToJson},
  21    platform::{CursorStyle, WindowOptions},
  22    AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, Entity, ImageData,
  23    ModelContext, ModelHandle, MutableAppContext, PathPromptOptions, PromptLevel, RenderContext,
  24    Task, View, ViewContext, ViewHandle, WeakViewHandle,
  25};
  26use language::LanguageRegistry;
  27use log::error;
  28pub use pane::*;
  29pub use pane_group::*;
  30use postage::prelude::Stream;
  31use project::{fs, Fs, Project, ProjectEntryId, ProjectPath, ProjectStore, Worktree, WorktreeId};
  32use serde::Deserialize;
  33use settings::Settings;
  34use sidebar::{Side, Sidebar, SidebarButtons, ToggleSidebarItem, ToggleSidebarItemFocus};
  35use smallvec::SmallVec;
  36use status_bar::StatusBar;
  37pub use status_bar::StatusItemView;
  38use std::{
  39    any::{Any, TypeId},
  40    borrow::Cow,
  41    cell::RefCell,
  42    fmt,
  43    future::Future,
  44    path::{Path, PathBuf},
  45    rc::Rc,
  46    sync::{
  47        atomic::{AtomicBool, Ordering::SeqCst},
  48        Arc,
  49    },
  50};
  51use theme::{Theme, ThemeRegistry};
  52pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
  53use util::ResultExt;
  54use waiting_room::WaitingRoom;
  55
  56type ProjectItemBuilders = HashMap<
  57    TypeId,
  58    fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
  59>;
  60
  61type FollowableItemBuilder = fn(
  62    ViewHandle<Pane>,
  63    ModelHandle<Project>,
  64    &mut Option<proto::view::Variant>,
  65    &mut MutableAppContext,
  66) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
  67type FollowableItemBuilders = HashMap<
  68    TypeId,
  69    (
  70        FollowableItemBuilder,
  71        fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
  72    ),
  73>;
  74
  75#[derive(Clone, PartialEq)]
  76pub struct RemoveWorktreeFromProject(pub WorktreeId);
  77
  78actions!(
  79    workspace,
  80    [
  81        Open,
  82        NewFile,
  83        NewWindow,
  84        CloseWindow,
  85        AddFolderToProject,
  86        Unfollow,
  87        Save,
  88        SaveAs,
  89        SaveAll,
  90        ActivatePreviousPane,
  91        ActivateNextPane,
  92        FollowNextCollaborator,
  93    ]
  94);
  95
  96#[derive(Clone, PartialEq)]
  97pub struct OpenPaths {
  98    pub paths: Vec<PathBuf>,
  99}
 100
 101#[derive(Clone, Deserialize, PartialEq)]
 102pub struct ToggleProjectOnline {
 103    #[serde(skip_deserializing)]
 104    pub project: Option<ModelHandle<Project>>,
 105}
 106
 107#[derive(Clone, PartialEq)]
 108pub struct ToggleFollow(pub PeerId);
 109
 110#[derive(Clone, PartialEq)]
 111pub struct JoinProject {
 112    pub contact: Arc<Contact>,
 113    pub project_index: usize,
 114}
 115
 116impl_internal_actions!(
 117    workspace,
 118    [
 119        OpenPaths,
 120        ToggleFollow,
 121        JoinProject,
 122        RemoveWorktreeFromProject
 123    ]
 124);
 125impl_actions!(workspace, [ToggleProjectOnline]);
 126
 127pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
 128    pane::init(cx);
 129
 130    cx.add_global_action(open);
 131    cx.add_global_action({
 132        let app_state = Arc::downgrade(&app_state);
 133        move |action: &OpenPaths, cx: &mut MutableAppContext| {
 134            if let Some(app_state) = app_state.upgrade() {
 135                open_paths(&action.paths, &app_state, cx).detach();
 136            }
 137        }
 138    });
 139    cx.add_global_action({
 140        let app_state = Arc::downgrade(&app_state);
 141        move |_: &NewFile, cx: &mut MutableAppContext| {
 142            if let Some(app_state) = app_state.upgrade() {
 143                open_new(&app_state, cx)
 144            }
 145        }
 146    });
 147    cx.add_global_action({
 148        let app_state = Arc::downgrade(&app_state);
 149        move |_: &NewWindow, cx: &mut MutableAppContext| {
 150            if let Some(app_state) = app_state.upgrade() {
 151                open_new(&app_state, cx)
 152            }
 153        }
 154    });
 155    cx.add_global_action({
 156        let app_state = Arc::downgrade(&app_state);
 157        move |action: &JoinProject, cx: &mut MutableAppContext| {
 158            if let Some(app_state) = app_state.upgrade() {
 159                join_project(action.contact.clone(), action.project_index, &app_state, cx);
 160            }
 161        }
 162    });
 163
 164    cx.add_async_action(Workspace::toggle_follow);
 165    cx.add_async_action(Workspace::follow_next_collaborator);
 166    cx.add_async_action(Workspace::close);
 167    cx.add_async_action(Workspace::save_all);
 168    cx.add_action(Workspace::add_folder_to_project);
 169    cx.add_action(Workspace::remove_folder_from_project);
 170    cx.add_action(Workspace::toggle_project_online);
 171    cx.add_action(
 172        |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
 173            let pane = workspace.active_pane().clone();
 174            workspace.unfollow(&pane, cx);
 175        },
 176    );
 177    cx.add_action(
 178        |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
 179            workspace.save_active_item(false, cx).detach_and_log_err(cx);
 180        },
 181    );
 182    cx.add_action(
 183        |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
 184            workspace.save_active_item(true, cx).detach_and_log_err(cx);
 185        },
 186    );
 187    cx.add_action(Workspace::toggle_sidebar_item);
 188    cx.add_action(Workspace::toggle_sidebar_item_focus);
 189    cx.add_action(Workspace::focus_center);
 190    cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
 191        workspace.activate_previous_pane(cx)
 192    });
 193    cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
 194        workspace.activate_next_pane(cx)
 195    });
 196
 197    let client = &app_state.client;
 198    client.add_view_request_handler(Workspace::handle_follow);
 199    client.add_view_message_handler(Workspace::handle_unfollow);
 200    client.add_view_message_handler(Workspace::handle_update_followers);
 201}
 202
 203pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
 204    cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
 205        builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
 206            let item = model.downcast::<I::Item>().unwrap();
 207            Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
 208        });
 209    });
 210}
 211
 212pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
 213    cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
 214        builders.insert(
 215            TypeId::of::<I>(),
 216            (
 217                |pane, project, state, cx| {
 218                    I::from_state_proto(pane, project, state, cx).map(|task| {
 219                        cx.foreground()
 220                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
 221                    })
 222                },
 223                |this| Box::new(this.downcast::<I>().unwrap()),
 224            ),
 225        );
 226    });
 227}
 228
 229pub struct AppState {
 230    pub languages: Arc<LanguageRegistry>,
 231    pub themes: Arc<ThemeRegistry>,
 232    pub client: Arc<client::Client>,
 233    pub user_store: ModelHandle<client::UserStore>,
 234    pub project_store: ModelHandle<ProjectStore>,
 235    pub fs: Arc<dyn fs::Fs>,
 236    pub build_window_options: fn() -> WindowOptions<'static>,
 237    pub initialize_workspace: fn(&mut Workspace, &Arc<AppState>, &mut ViewContext<Workspace>),
 238}
 239
 240pub trait Item: View {
 241    fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
 242    fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
 243        false
 244    }
 245    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
 246    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 247    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 248    fn is_singleton(&self, cx: &AppContext) -> bool;
 249    fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
 250    fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
 251    where
 252        Self: Sized,
 253    {
 254        None
 255    }
 256    fn is_dirty(&self, _: &AppContext) -> bool {
 257        false
 258    }
 259    fn has_conflict(&self, _: &AppContext) -> bool {
 260        false
 261    }
 262    fn can_save(&self, cx: &AppContext) -> bool;
 263    fn save(
 264        &mut self,
 265        project: ModelHandle<Project>,
 266        cx: &mut ViewContext<Self>,
 267    ) -> Task<Result<()>>;
 268    fn save_as(
 269        &mut self,
 270        project: ModelHandle<Project>,
 271        abs_path: PathBuf,
 272        cx: &mut ViewContext<Self>,
 273    ) -> Task<Result<()>>;
 274    fn reload(
 275        &mut self,
 276        project: ModelHandle<Project>,
 277        cx: &mut ViewContext<Self>,
 278    ) -> Task<Result<()>>;
 279    fn should_activate_item_on_event(_: &Self::Event) -> bool {
 280        false
 281    }
 282    fn should_close_item_on_event(_: &Self::Event) -> bool {
 283        false
 284    }
 285    fn should_update_tab_on_event(_: &Self::Event) -> bool {
 286        false
 287    }
 288    fn act_as_type(
 289        &self,
 290        type_id: TypeId,
 291        self_handle: &ViewHandle<Self>,
 292        _: &AppContext,
 293    ) -> Option<AnyViewHandle> {
 294        if TypeId::of::<Self>() == type_id {
 295            Some(self_handle.into())
 296        } else {
 297            None
 298        }
 299    }
 300}
 301
 302pub trait ProjectItem: Item {
 303    type Item: project::Item;
 304
 305    fn for_project_item(
 306        project: ModelHandle<Project>,
 307        item: ModelHandle<Self::Item>,
 308        cx: &mut ViewContext<Self>,
 309    ) -> Self;
 310}
 311
 312pub trait FollowableItem: Item {
 313    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 314    fn from_state_proto(
 315        pane: ViewHandle<Pane>,
 316        project: ModelHandle<Project>,
 317        state: &mut Option<proto::view::Variant>,
 318        cx: &mut MutableAppContext,
 319    ) -> Option<Task<Result<ViewHandle<Self>>>>;
 320    fn add_event_to_update_proto(
 321        &self,
 322        event: &Self::Event,
 323        update: &mut Option<proto::update_view::Variant>,
 324        cx: &AppContext,
 325    ) -> bool;
 326    fn apply_update_proto(
 327        &mut self,
 328        message: proto::update_view::Variant,
 329        cx: &mut ViewContext<Self>,
 330    ) -> Result<()>;
 331
 332    fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
 333    fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
 334}
 335
 336pub trait FollowableItemHandle: ItemHandle {
 337    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
 338    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 339    fn add_event_to_update_proto(
 340        &self,
 341        event: &dyn Any,
 342        update: &mut Option<proto::update_view::Variant>,
 343        cx: &AppContext,
 344    ) -> bool;
 345    fn apply_update_proto(
 346        &self,
 347        message: proto::update_view::Variant,
 348        cx: &mut MutableAppContext,
 349    ) -> Result<()>;
 350    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
 351}
 352
 353impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
 354    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
 355        self.update(cx, |this, cx| {
 356            this.set_leader_replica_id(leader_replica_id, cx)
 357        })
 358    }
 359
 360    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
 361        self.read(cx).to_state_proto(cx)
 362    }
 363
 364    fn add_event_to_update_proto(
 365        &self,
 366        event: &dyn Any,
 367        update: &mut Option<proto::update_view::Variant>,
 368        cx: &AppContext,
 369    ) -> bool {
 370        if let Some(event) = event.downcast_ref() {
 371            self.read(cx).add_event_to_update_proto(event, update, cx)
 372        } else {
 373            false
 374        }
 375    }
 376
 377    fn apply_update_proto(
 378        &self,
 379        message: proto::update_view::Variant,
 380        cx: &mut MutableAppContext,
 381    ) -> Result<()> {
 382        self.update(cx, |this, cx| this.apply_update_proto(message, cx))
 383    }
 384
 385    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
 386        if let Some(event) = event.downcast_ref() {
 387            T::should_unfollow_on_event(event, cx)
 388        } else {
 389            false
 390        }
 391    }
 392}
 393
 394pub trait ItemHandle: 'static + fmt::Debug {
 395    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
 396    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 397    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 398    fn is_singleton(&self, cx: &AppContext) -> bool;
 399    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 400    fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext);
 401    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
 402    fn added_to_pane(
 403        &self,
 404        workspace: &mut Workspace,
 405        pane: ViewHandle<Pane>,
 406        cx: &mut ViewContext<Workspace>,
 407    );
 408    fn deactivated(&self, cx: &mut MutableAppContext);
 409    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
 410    fn id(&self) -> usize;
 411    fn to_any(&self) -> AnyViewHandle;
 412    fn is_dirty(&self, cx: &AppContext) -> bool;
 413    fn has_conflict(&self, cx: &AppContext) -> bool;
 414    fn can_save(&self, cx: &AppContext) -> bool;
 415    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
 416    fn save_as(
 417        &self,
 418        project: ModelHandle<Project>,
 419        abs_path: PathBuf,
 420        cx: &mut MutableAppContext,
 421    ) -> Task<Result<()>>;
 422    fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)
 423        -> Task<Result<()>>;
 424    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
 425    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
 426    fn on_release(
 427        &self,
 428        cx: &mut MutableAppContext,
 429        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
 430    ) -> gpui::Subscription;
 431}
 432
 433pub trait WeakItemHandle {
 434    fn id(&self) -> usize;
 435    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
 436}
 437
 438impl dyn ItemHandle {
 439    pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
 440        self.to_any().downcast()
 441    }
 442
 443    pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
 444        self.act_as_type(TypeId::of::<T>(), cx)
 445            .and_then(|t| t.downcast())
 446    }
 447}
 448
 449impl<T: Item> ItemHandle for ViewHandle<T> {
 450    fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
 451        self.read(cx).tab_content(style, cx)
 452    }
 453
 454    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 455        self.read(cx).project_path(cx)
 456    }
 457
 458    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
 459        self.read(cx).project_entry_ids(cx)
 460    }
 461
 462    fn is_singleton(&self, cx: &AppContext) -> bool {
 463        self.read(cx).is_singleton(cx)
 464    }
 465
 466    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 467        Box::new(self.clone())
 468    }
 469
 470    fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext) {
 471        self.update(cx, |item, cx| {
 472            item.set_nav_history(ItemNavHistory::new(nav_history, &cx.handle()), cx);
 473        })
 474    }
 475
 476    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
 477        self.update(cx, |item, cx| {
 478            cx.add_option_view(|cx| item.clone_on_split(cx))
 479        })
 480        .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 481    }
 482
 483    fn added_to_pane(
 484        &self,
 485        workspace: &mut Workspace,
 486        pane: ViewHandle<Pane>,
 487        cx: &mut ViewContext<Workspace>,
 488    ) {
 489        if let Some(followed_item) = self.to_followable_item_handle(cx) {
 490            if let Some(message) = followed_item.to_state_proto(cx) {
 491                workspace.update_followers(
 492                    proto::update_followers::Variant::CreateView(proto::View {
 493                        id: followed_item.id() as u64,
 494                        variant: Some(message),
 495                        leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
 496                    }),
 497                    cx,
 498                );
 499            }
 500        }
 501
 502        let pending_update = Rc::new(RefCell::new(None));
 503        let pending_update_scheduled = Rc::new(AtomicBool::new(false));
 504        let pane = pane.downgrade();
 505        cx.subscribe(self, move |workspace, item, event, cx| {
 506            let pane = if let Some(pane) = pane.upgrade(cx) {
 507                pane
 508            } else {
 509                log::error!("unexpected item event after pane was dropped");
 510                return;
 511            };
 512
 513            if let Some(item) = item.to_followable_item_handle(cx) {
 514                let leader_id = workspace.leader_for_pane(&pane);
 515
 516                if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
 517                    workspace.unfollow(&pane, cx);
 518                }
 519
 520                if item.add_event_to_update_proto(event, &mut *pending_update.borrow_mut(), cx)
 521                    && !pending_update_scheduled.load(SeqCst)
 522                {
 523                    pending_update_scheduled.store(true, SeqCst);
 524                    cx.after_window_update({
 525                        let pending_update = pending_update.clone();
 526                        let pending_update_scheduled = pending_update_scheduled.clone();
 527                        move |this, cx| {
 528                            pending_update_scheduled.store(false, SeqCst);
 529                            this.update_followers(
 530                                proto::update_followers::Variant::UpdateView(proto::UpdateView {
 531                                    id: item.id() as u64,
 532                                    variant: pending_update.borrow_mut().take(),
 533                                    leader_id: leader_id.map(|id| id.0),
 534                                }),
 535                                cx,
 536                            );
 537                        }
 538                    });
 539                }
 540            }
 541
 542            if T::should_close_item_on_event(event) {
 543                Pane::close_item(workspace, pane, item.id(), cx).detach_and_log_err(cx);
 544                return;
 545            }
 546
 547            if T::should_activate_item_on_event(event) {
 548                pane.update(cx, |pane, cx| {
 549                    if let Some(ix) = pane.index_for_item(&item) {
 550                        pane.activate_item(ix, true, true, cx);
 551                        pane.activate(cx);
 552                    }
 553                });
 554            }
 555
 556            if T::should_update_tab_on_event(event) {
 557                pane.update(cx, |_, cx| {
 558                    cx.emit(pane::Event::ChangeItemTitle);
 559                    cx.notify();
 560                });
 561            }
 562        })
 563        .detach();
 564    }
 565
 566    fn deactivated(&self, cx: &mut MutableAppContext) {
 567        self.update(cx, |this, cx| this.deactivated(cx));
 568    }
 569
 570    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {
 571        self.update(cx, |this, cx| this.navigate(data, cx))
 572    }
 573
 574    fn id(&self) -> usize {
 575        self.id()
 576    }
 577
 578    fn to_any(&self) -> AnyViewHandle {
 579        self.into()
 580    }
 581
 582    fn is_dirty(&self, cx: &AppContext) -> bool {
 583        self.read(cx).is_dirty(cx)
 584    }
 585
 586    fn has_conflict(&self, cx: &AppContext) -> bool {
 587        self.read(cx).has_conflict(cx)
 588    }
 589
 590    fn can_save(&self, cx: &AppContext) -> bool {
 591        self.read(cx).can_save(cx)
 592    }
 593
 594    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
 595        self.update(cx, |item, cx| item.save(project, cx))
 596    }
 597
 598    fn save_as(
 599        &self,
 600        project: ModelHandle<Project>,
 601        abs_path: PathBuf,
 602        cx: &mut MutableAppContext,
 603    ) -> Task<anyhow::Result<()>> {
 604        self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
 605    }
 606
 607    fn reload(
 608        &self,
 609        project: ModelHandle<Project>,
 610        cx: &mut MutableAppContext,
 611    ) -> Task<Result<()>> {
 612        self.update(cx, |item, cx| item.reload(project, cx))
 613    }
 614
 615    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
 616        self.read(cx).act_as_type(type_id, self, cx)
 617    }
 618
 619    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 620        if cx.has_global::<FollowableItemBuilders>() {
 621            let builders = cx.global::<FollowableItemBuilders>();
 622            let item = self.to_any();
 623            Some(builders.get(&item.view_type())?.1(item))
 624        } else {
 625            None
 626        }
 627    }
 628
 629    fn on_release(
 630        &self,
 631        cx: &mut MutableAppContext,
 632        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
 633    ) -> gpui::Subscription {
 634        cx.observe_release(self, move |_, cx| callback(cx))
 635    }
 636}
 637
 638impl Into<AnyViewHandle> for Box<dyn ItemHandle> {
 639    fn into(self) -> AnyViewHandle {
 640        self.to_any()
 641    }
 642}
 643
 644impl Clone for Box<dyn ItemHandle> {
 645    fn clone(&self) -> Box<dyn ItemHandle> {
 646        self.boxed_clone()
 647    }
 648}
 649
 650impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
 651    fn id(&self) -> usize {
 652        self.id()
 653    }
 654
 655    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 656        self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
 657    }
 658}
 659
 660pub trait Notification: View {
 661    fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool;
 662}
 663
 664pub trait NotificationHandle {
 665    fn id(&self) -> usize;
 666    fn to_any(&self) -> AnyViewHandle;
 667}
 668
 669impl<T: Notification> NotificationHandle for ViewHandle<T> {
 670    fn id(&self) -> usize {
 671        self.id()
 672    }
 673
 674    fn to_any(&self) -> AnyViewHandle {
 675        self.into()
 676    }
 677}
 678
 679impl Into<AnyViewHandle> for &dyn NotificationHandle {
 680    fn into(self) -> AnyViewHandle {
 681        self.to_any()
 682    }
 683}
 684
 685impl AppState {
 686    #[cfg(any(test, feature = "test-support"))]
 687    pub fn test(cx: &mut MutableAppContext) -> Arc<Self> {
 688        let settings = Settings::test(cx);
 689        cx.set_global(settings);
 690
 691        let fs = project::FakeFs::new(cx.background().clone());
 692        let languages = Arc::new(LanguageRegistry::test());
 693        let http_client = client::test::FakeHttpClient::with_404_response();
 694        let client = Client::new(http_client.clone());
 695        let project_store = cx.add_model(|_| ProjectStore::new(project::Db::open_fake()));
 696        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 697        let themes = ThemeRegistry::new((), cx.font_cache().clone());
 698        Arc::new(Self {
 699            client,
 700            themes,
 701            fs,
 702            languages,
 703            user_store,
 704            project_store,
 705            initialize_workspace: |_, _, _| {},
 706            build_window_options: || Default::default(),
 707        })
 708    }
 709}
 710
 711pub enum Event {
 712    PaneAdded(ViewHandle<Pane>),
 713    ContactRequestedJoin(u64),
 714}
 715
 716pub struct Workspace {
 717    weak_self: WeakViewHandle<Self>,
 718    client: Arc<Client>,
 719    user_store: ModelHandle<client::UserStore>,
 720    remote_entity_subscription: Option<Subscription>,
 721    fs: Arc<dyn Fs>,
 722    modal: Option<AnyViewHandle>,
 723    center: PaneGroup,
 724    left_sidebar: ViewHandle<Sidebar>,
 725    right_sidebar: ViewHandle<Sidebar>,
 726    panes: Vec<ViewHandle<Pane>>,
 727    active_pane: ViewHandle<Pane>,
 728    status_bar: ViewHandle<StatusBar>,
 729    notifications: Vec<(TypeId, usize, Box<dyn NotificationHandle>)>,
 730    project: ModelHandle<Project>,
 731    leader_state: LeaderState,
 732    follower_states_by_leader: FollowerStatesByLeader,
 733    last_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,
 734    window_edited: bool,
 735    _observe_current_user: Task<()>,
 736}
 737
 738#[derive(Default)]
 739struct LeaderState {
 740    followers: HashSet<PeerId>,
 741}
 742
 743type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
 744
 745#[derive(Default)]
 746struct FollowerState {
 747    active_view_id: Option<u64>,
 748    items_by_leader_view_id: HashMap<u64, FollowerItem>,
 749}
 750
 751#[derive(Debug)]
 752enum FollowerItem {
 753    Loading(Vec<proto::update_view::Variant>),
 754    Loaded(Box<dyn FollowableItemHandle>),
 755}
 756
 757impl Workspace {
 758    pub fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
 759        cx.observe(&project, |_, project, cx| {
 760            if project.read(cx).is_read_only() {
 761                cx.blur();
 762            }
 763            cx.notify()
 764        })
 765        .detach();
 766
 767        cx.subscribe(&project, move |this, project, event, cx| {
 768            match event {
 769                project::Event::RemoteIdChanged(remote_id) => {
 770                    this.project_remote_id_changed(*remote_id, cx);
 771                }
 772                project::Event::CollaboratorLeft(peer_id) => {
 773                    this.collaborator_left(*peer_id, cx);
 774                }
 775                project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded => {
 776                    this.update_window_title(cx);
 777                }
 778                _ => {}
 779            }
 780            if project.read(cx).is_read_only() {
 781                cx.blur();
 782            }
 783            cx.notify()
 784        })
 785        .detach();
 786
 787        let pane = cx.add_view(|cx| Pane::new(cx));
 788        let pane_id = pane.id();
 789        cx.subscribe(&pane, move |this, _, event, cx| {
 790            this.handle_pane_event(pane_id, event, cx)
 791        })
 792        .detach();
 793        cx.focus(&pane);
 794        cx.emit(Event::PaneAdded(pane.clone()));
 795
 796        let fs = project.read(cx).fs().clone();
 797        let user_store = project.read(cx).user_store();
 798        let client = project.read(cx).client();
 799        let mut current_user = user_store.read(cx).watch_current_user().clone();
 800        let mut connection_status = client.status().clone();
 801        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 802            current_user.recv().await;
 803            connection_status.recv().await;
 804            let mut stream =
 805                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 806
 807            while stream.recv().await.is_some() {
 808                cx.update(|cx| {
 809                    if let Some(this) = this.upgrade(cx) {
 810                        this.update(cx, |_, cx| cx.notify());
 811                    }
 812                })
 813            }
 814        });
 815
 816        let weak_self = cx.weak_handle();
 817
 818        cx.emit_global(WorkspaceCreated(weak_self.clone()));
 819
 820        let left_sidebar = cx.add_view(|_| Sidebar::new(Side::Left));
 821        let right_sidebar = cx.add_view(|_| Sidebar::new(Side::Right));
 822        let left_sidebar_buttons = cx.add_view(|cx| SidebarButtons::new(left_sidebar.clone(), cx));
 823        let right_sidebar_buttons =
 824            cx.add_view(|cx| SidebarButtons::new(right_sidebar.clone(), cx));
 825        let status_bar = cx.add_view(|cx| {
 826            let mut status_bar = StatusBar::new(&pane.clone(), cx);
 827            status_bar.add_left_item(left_sidebar_buttons, cx);
 828            status_bar.add_right_item(right_sidebar_buttons, cx);
 829            status_bar
 830        });
 831
 832        let mut this = Workspace {
 833            modal: None,
 834            weak_self,
 835            center: PaneGroup::new(pane.clone()),
 836            panes: vec![pane.clone()],
 837            active_pane: pane.clone(),
 838            status_bar,
 839            notifications: Default::default(),
 840            client,
 841            remote_entity_subscription: None,
 842            user_store,
 843            fs,
 844            left_sidebar,
 845            right_sidebar,
 846            project,
 847            leader_state: Default::default(),
 848            follower_states_by_leader: Default::default(),
 849            last_leaders_by_pane: Default::default(),
 850            window_edited: false,
 851            _observe_current_user,
 852        };
 853        this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
 854        cx.defer(|this, cx| this.update_window_title(cx));
 855
 856        this
 857    }
 858
 859    pub fn weak_handle(&self) -> WeakViewHandle<Self> {
 860        self.weak_self.clone()
 861    }
 862
 863    pub fn left_sidebar(&self) -> &ViewHandle<Sidebar> {
 864        &self.left_sidebar
 865    }
 866
 867    pub fn right_sidebar(&self) -> &ViewHandle<Sidebar> {
 868        &self.right_sidebar
 869    }
 870
 871    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
 872        &self.status_bar
 873    }
 874
 875    pub fn user_store(&self) -> &ModelHandle<UserStore> {
 876        &self.user_store
 877    }
 878
 879    pub fn project(&self) -> &ModelHandle<Project> {
 880        &self.project
 881    }
 882
 883    pub fn worktrees<'a>(
 884        &self,
 885        cx: &'a AppContext,
 886    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 887        self.project.read(cx).worktrees(cx)
 888    }
 889
 890    pub fn visible_worktrees<'a>(
 891        &self,
 892        cx: &'a AppContext,
 893    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 894        self.project.read(cx).visible_worktrees(cx)
 895    }
 896
 897    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
 898        let futures = self
 899            .worktrees(cx)
 900            .filter_map(|worktree| worktree.read(cx).as_local())
 901            .map(|worktree| worktree.scan_complete())
 902            .collect::<Vec<_>>();
 903        async move {
 904            for future in futures {
 905                future.await;
 906            }
 907        }
 908    }
 909
 910    fn close(&mut self, _: &CloseWindow, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 911        let prepare = self.prepare_to_close(cx);
 912        Some(cx.spawn(|this, mut cx| async move {
 913            if prepare.await? {
 914                this.update(&mut cx, |_, cx| {
 915                    let window_id = cx.window_id();
 916                    cx.remove_window(window_id);
 917                });
 918            }
 919            Ok(())
 920        }))
 921    }
 922
 923    pub fn prepare_to_close(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
 924        self.save_all_internal(true, cx)
 925    }
 926
 927    fn save_all(&mut self, _: &SaveAll, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 928        let save_all = self.save_all_internal(false, cx);
 929        Some(cx.foreground().spawn(async move {
 930            save_all.await?;
 931            Ok(())
 932        }))
 933    }
 934
 935    fn save_all_internal(
 936        &mut self,
 937        should_prompt_to_save: bool,
 938        cx: &mut ViewContext<Self>,
 939    ) -> Task<Result<bool>> {
 940        let dirty_items = self
 941            .panes
 942            .iter()
 943            .flat_map(|pane| {
 944                pane.read(cx).items().filter_map(|item| {
 945                    if item.is_dirty(cx) {
 946                        Some((pane.clone(), item.boxed_clone()))
 947                    } else {
 948                        None
 949                    }
 950                })
 951            })
 952            .collect::<Vec<_>>();
 953
 954        let project = self.project.clone();
 955        cx.spawn_weak(|_, mut cx| async move {
 956            // let mut saved_project_entry_ids = HashSet::default();
 957            for (pane, item) in dirty_items {
 958                let (is_singl, project_entry_ids) =
 959                    cx.read(|cx| (item.is_singleton(cx), item.project_entry_ids(cx)));
 960                if is_singl || !project_entry_ids.is_empty() {
 961                    if let Some(ix) =
 962                        pane.read_with(&cx, |pane, _| pane.index_for_item(item.as_ref()))
 963                    {
 964                        if !Pane::save_item(
 965                            project.clone(),
 966                            &pane,
 967                            ix,
 968                            &item,
 969                            should_prompt_to_save,
 970                            &mut cx,
 971                        )
 972                        .await?
 973                        {
 974                            return Ok(false);
 975                        }
 976                    }
 977                }
 978            }
 979            Ok(true)
 980        })
 981    }
 982
 983    pub fn open_paths(
 984        &mut self,
 985        mut abs_paths: Vec<PathBuf>,
 986        visible: bool,
 987        cx: &mut ViewContext<Self>,
 988    ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
 989        let fs = self.fs.clone();
 990
 991        // Sort the paths to ensure we add worktrees for parents before their children.
 992        abs_paths.sort_unstable();
 993        cx.spawn(|this, mut cx| async move {
 994            let mut entries = Vec::new();
 995            for path in &abs_paths {
 996                entries.push(
 997                    this.update(&mut cx, |this, cx| {
 998                        this.project_path_for_path(path, visible, cx)
 999                    })
1000                    .await
1001                    .log_err(),
1002                );
1003            }
1004
1005            let tasks = abs_paths
1006                .iter()
1007                .cloned()
1008                .zip(entries.into_iter())
1009                .map(|(abs_path, project_path)| {
1010                    let this = this.clone();
1011                    cx.spawn(|mut cx| {
1012                        let fs = fs.clone();
1013                        async move {
1014                            let (_worktree, project_path) = project_path?;
1015                            if fs.is_file(&abs_path).await {
1016                                Some(
1017                                    this.update(&mut cx, |this, cx| {
1018                                        this.open_path(project_path, true, cx)
1019                                    })
1020                                    .await,
1021                                )
1022                            } else {
1023                                None
1024                            }
1025                        }
1026                    })
1027                })
1028                .collect::<Vec<_>>();
1029
1030            futures::future::join_all(tasks).await
1031        })
1032    }
1033
1034    fn add_folder_to_project(&mut self, _: &AddFolderToProject, cx: &mut ViewContext<Self>) {
1035        let mut paths = cx.prompt_for_paths(PathPromptOptions {
1036            files: false,
1037            directories: true,
1038            multiple: true,
1039        });
1040        cx.spawn(|this, mut cx| async move {
1041            if let Some(paths) = paths.recv().await.flatten() {
1042                let results = this
1043                    .update(&mut cx, |this, cx| this.open_paths(paths, true, cx))
1044                    .await;
1045                for result in results {
1046                    if let Some(result) = result {
1047                        result.log_err();
1048                    }
1049                }
1050            }
1051        })
1052        .detach();
1053    }
1054
1055    fn remove_folder_from_project(
1056        &mut self,
1057        RemoveWorktreeFromProject(worktree_id): &RemoveWorktreeFromProject,
1058        cx: &mut ViewContext<Self>,
1059    ) {
1060        self.project
1061            .update(cx, |project, cx| project.remove_worktree(*worktree_id, cx));
1062    }
1063
1064    fn toggle_project_online(&mut self, action: &ToggleProjectOnline, cx: &mut ViewContext<Self>) {
1065        let project = action
1066            .project
1067            .clone()
1068            .unwrap_or_else(|| self.project.clone());
1069        project.update(cx, |project, cx| {
1070            let public = !project.is_online();
1071            project.set_online(public, cx);
1072        });
1073    }
1074
1075    fn project_path_for_path(
1076        &self,
1077        abs_path: &Path,
1078        visible: bool,
1079        cx: &mut ViewContext<Self>,
1080    ) -> Task<Result<(ModelHandle<Worktree>, ProjectPath)>> {
1081        let entry = self.project().update(cx, |project, cx| {
1082            project.find_or_create_local_worktree(abs_path, visible, cx)
1083        });
1084        cx.spawn(|_, cx| async move {
1085            let (worktree, path) = entry.await?;
1086            let worktree_id = worktree.read_with(&cx, |t, _| t.id());
1087            Ok((
1088                worktree,
1089                ProjectPath {
1090                    worktree_id,
1091                    path: path.into(),
1092                },
1093            ))
1094        })
1095    }
1096
1097    /// Returns the modal that was toggled closed if it was open.
1098    pub fn toggle_modal<V, F>(
1099        &mut self,
1100        cx: &mut ViewContext<Self>,
1101        add_view: F,
1102    ) -> Option<ViewHandle<V>>
1103    where
1104        V: 'static + View,
1105        F: FnOnce(&mut Self, &mut ViewContext<Self>) -> ViewHandle<V>,
1106    {
1107        cx.notify();
1108        // Whatever modal was visible is getting clobbered. If its the same type as V, then return
1109        // it. Otherwise, create a new modal and set it as active.
1110        let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
1111        if let Some(already_open_modal) = already_open_modal {
1112            cx.focus_self();
1113            Some(already_open_modal)
1114        } else {
1115            let modal = add_view(self, cx);
1116            cx.focus(&modal);
1117            self.modal = Some(modal.into());
1118            None
1119        }
1120    }
1121
1122    pub fn modal(&self) -> Option<&AnyViewHandle> {
1123        self.modal.as_ref()
1124    }
1125
1126    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
1127        if self.modal.take().is_some() {
1128            cx.focus(&self.active_pane);
1129            cx.notify();
1130        }
1131    }
1132
1133    pub fn show_notification<V: Notification>(
1134        &mut self,
1135        id: usize,
1136        cx: &mut ViewContext<Self>,
1137        build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
1138    ) {
1139        let type_id = TypeId::of::<V>();
1140        if self
1141            .notifications
1142            .iter()
1143            .all(|(existing_type_id, existing_id, _)| {
1144                (*existing_type_id, *existing_id) != (type_id, id)
1145            })
1146        {
1147            let notification = build_notification(cx);
1148            cx.subscribe(&notification, move |this, handle, event, cx| {
1149                if handle.read(cx).should_dismiss_notification_on_event(event) {
1150                    this.dismiss_notification(type_id, id, cx);
1151                }
1152            })
1153            .detach();
1154            self.notifications
1155                .push((type_id, id, Box::new(notification)));
1156            cx.notify();
1157        }
1158    }
1159
1160    fn dismiss_notification(&mut self, type_id: TypeId, id: usize, cx: &mut ViewContext<Self>) {
1161        self.notifications
1162            .retain(|(existing_type_id, existing_id, _)| {
1163                if (*existing_type_id, *existing_id) == (type_id, id) {
1164                    cx.notify();
1165                    false
1166                } else {
1167                    true
1168                }
1169            });
1170    }
1171
1172    pub fn items<'a>(
1173        &'a self,
1174        cx: &'a AppContext,
1175    ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1176        self.panes.iter().flat_map(|pane| pane.read(cx).items())
1177    }
1178
1179    pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
1180        self.items_of_type(cx).max_by_key(|item| item.id())
1181    }
1182
1183    pub fn items_of_type<'a, T: Item>(
1184        &'a self,
1185        cx: &'a AppContext,
1186    ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
1187        self.panes
1188            .iter()
1189            .flat_map(|pane| pane.read(cx).items_of_type())
1190    }
1191
1192    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1193        self.active_pane().read(cx).active_item()
1194    }
1195
1196    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1197        self.active_item(cx).and_then(|item| item.project_path(cx))
1198    }
1199
1200    pub fn save_active_item(
1201        &mut self,
1202        force_name_change: bool,
1203        cx: &mut ViewContext<Self>,
1204    ) -> Task<Result<()>> {
1205        let project = self.project.clone();
1206        if let Some(item) = self.active_item(cx) {
1207            if !force_name_change && item.can_save(cx) {
1208                if item.has_conflict(cx.as_ref()) {
1209                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1210
1211                    let mut answer = cx.prompt(
1212                        PromptLevel::Warning,
1213                        CONFLICT_MESSAGE,
1214                        &["Overwrite", "Cancel"],
1215                    );
1216                    cx.spawn(|_, mut cx| async move {
1217                        let answer = answer.recv().await;
1218                        if answer == Some(0) {
1219                            cx.update(|cx| item.save(project, cx)).await?;
1220                        }
1221                        Ok(())
1222                    })
1223                } else {
1224                    item.save(project, cx)
1225                }
1226            } else if item.is_singleton(cx) {
1227                let worktree = self.worktrees(cx).next();
1228                let start_abs_path = worktree
1229                    .and_then(|w| w.read(cx).as_local())
1230                    .map_or(Path::new(""), |w| w.abs_path())
1231                    .to_path_buf();
1232                let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1233                cx.spawn(|_, mut cx| async move {
1234                    if let Some(abs_path) = abs_path.recv().await.flatten() {
1235                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1236                    }
1237                    Ok(())
1238                })
1239            } else {
1240                Task::ready(Ok(()))
1241            }
1242        } else {
1243            Task::ready(Ok(()))
1244        }
1245    }
1246
1247    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1248        let sidebar = match action.side {
1249            Side::Left => &mut self.left_sidebar,
1250            Side::Right => &mut self.right_sidebar,
1251        };
1252        let active_item = sidebar.update(cx, |sidebar, cx| {
1253            sidebar.toggle_item(action.item_index, cx);
1254            sidebar.active_item().map(|item| item.to_any())
1255        });
1256        if let Some(active_item) = active_item {
1257            cx.focus(active_item);
1258        } else {
1259            cx.focus_self();
1260        }
1261        cx.notify();
1262    }
1263
1264    pub fn toggle_sidebar_item_focus(
1265        &mut self,
1266        action: &ToggleSidebarItemFocus,
1267        cx: &mut ViewContext<Self>,
1268    ) {
1269        let sidebar = match action.side {
1270            Side::Left => &mut self.left_sidebar,
1271            Side::Right => &mut self.right_sidebar,
1272        };
1273        let active_item = sidebar.update(cx, |sidebar, cx| {
1274            sidebar.activate_item(action.item_index, cx);
1275            sidebar.active_item().cloned()
1276        });
1277        if let Some(active_item) = active_item {
1278            if active_item.is_focused(cx) {
1279                cx.focus_self();
1280            } else {
1281                cx.focus(active_item.to_any());
1282            }
1283        }
1284        cx.notify();
1285    }
1286
1287    pub fn focus_center(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
1288        cx.focus_self();
1289        cx.notify();
1290    }
1291
1292    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1293        let pane = cx.add_view(|cx| Pane::new(cx));
1294        let pane_id = pane.id();
1295        cx.subscribe(&pane, move |this, _, event, cx| {
1296            this.handle_pane_event(pane_id, event, cx)
1297        })
1298        .detach();
1299        self.panes.push(pane.clone());
1300        self.activate_pane(pane.clone(), cx);
1301        cx.emit(Event::PaneAdded(pane.clone()));
1302        pane
1303    }
1304
1305    pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1306        let pane = self.active_pane().clone();
1307        Pane::add_item(self, pane, item, true, true, cx);
1308    }
1309
1310    pub fn open_path(
1311        &mut self,
1312        path: impl Into<ProjectPath>,
1313        focus_item: bool,
1314        cx: &mut ViewContext<Self>,
1315    ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1316        let pane = self.active_pane().downgrade();
1317        let task = self.load_path(path.into(), cx);
1318        cx.spawn(|this, mut cx| async move {
1319            let (project_entry_id, build_item) = task.await?;
1320            let pane = pane
1321                .upgrade(&cx)
1322                .ok_or_else(|| anyhow!("pane was closed"))?;
1323            this.update(&mut cx, |this, cx| {
1324                Ok(Pane::open_item(
1325                    this,
1326                    pane,
1327                    project_entry_id,
1328                    focus_item,
1329                    cx,
1330                    build_item,
1331                ))
1332            })
1333        })
1334    }
1335
1336    pub(crate) fn load_path(
1337        &mut self,
1338        path: ProjectPath,
1339        cx: &mut ViewContext<Self>,
1340    ) -> Task<
1341        Result<(
1342            ProjectEntryId,
1343            impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1344        )>,
1345    > {
1346        let project = self.project().clone();
1347        let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1348        let window_id = cx.window_id();
1349        cx.as_mut().spawn(|mut cx| async move {
1350            let (project_entry_id, project_item) = project_item.await?;
1351            let build_item = cx.update(|cx| {
1352                cx.default_global::<ProjectItemBuilders>()
1353                    .get(&project_item.model_type())
1354                    .ok_or_else(|| anyhow!("no item builder for project item"))
1355                    .cloned()
1356            })?;
1357            let build_item =
1358                move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1359            Ok((project_entry_id, build_item))
1360        })
1361    }
1362
1363    pub fn open_project_item<T>(
1364        &mut self,
1365        project_item: ModelHandle<T::Item>,
1366        cx: &mut ViewContext<Self>,
1367    ) -> ViewHandle<T>
1368    where
1369        T: ProjectItem,
1370    {
1371        use project::Item as _;
1372
1373        let entry_id = project_item.read(cx).entry_id(cx);
1374        if let Some(item) = entry_id
1375            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1376            .and_then(|item| item.downcast())
1377        {
1378            self.activate_item(&item, cx);
1379            return item;
1380        }
1381
1382        let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1383        self.add_item(Box::new(item.clone()), cx);
1384        item
1385    }
1386
1387    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1388        let result = self.panes.iter().find_map(|pane| {
1389            if let Some(ix) = pane.read(cx).index_for_item(item) {
1390                Some((pane.clone(), ix))
1391            } else {
1392                None
1393            }
1394        });
1395        if let Some((pane, ix)) = result {
1396            self.activate_pane(pane.clone(), cx);
1397            pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, cx));
1398            true
1399        } else {
1400            false
1401        }
1402    }
1403
1404    pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1405        let next_pane = {
1406            let panes = self.center.panes();
1407            let ix = panes
1408                .iter()
1409                .position(|pane| **pane == self.active_pane)
1410                .unwrap();
1411            let next_ix = (ix + 1) % panes.len();
1412            panes[next_ix].clone()
1413        };
1414        self.activate_pane(next_pane, cx);
1415    }
1416
1417    pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1418        let prev_pane = {
1419            let panes = self.center.panes();
1420            let ix = panes
1421                .iter()
1422                .position(|pane| **pane == self.active_pane)
1423                .unwrap();
1424            let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1425            panes[prev_ix].clone()
1426        };
1427        self.activate_pane(prev_pane, cx);
1428    }
1429
1430    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1431        if self.active_pane != pane {
1432            self.active_pane = pane.clone();
1433            self.status_bar.update(cx, |status_bar, cx| {
1434                status_bar.set_active_pane(&self.active_pane, cx);
1435            });
1436            self.active_item_path_changed(cx);
1437            cx.focus(&self.active_pane);
1438            cx.notify();
1439        }
1440
1441        self.update_followers(
1442            proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1443                id: self.active_item(cx).map(|item| item.id() as u64),
1444                leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1445            }),
1446            cx,
1447        );
1448    }
1449
1450    fn handle_pane_event(
1451        &mut self,
1452        pane_id: usize,
1453        event: &pane::Event,
1454        cx: &mut ViewContext<Self>,
1455    ) {
1456        if let Some(pane) = self.pane(pane_id) {
1457            match event {
1458                pane::Event::Split(direction) => {
1459                    self.split_pane(pane, *direction, cx);
1460                }
1461                pane::Event::Remove => {
1462                    self.remove_pane(pane, cx);
1463                }
1464                pane::Event::Activate => {
1465                    self.activate_pane(pane, cx);
1466                }
1467                pane::Event::ActivateItem { local } => {
1468                    if *local {
1469                        self.unfollow(&pane, cx);
1470                    }
1471                    if pane == self.active_pane {
1472                        self.active_item_path_changed(cx);
1473                    }
1474                }
1475                pane::Event::ChangeItemTitle => {
1476                    if pane == self.active_pane {
1477                        self.active_item_path_changed(cx);
1478                    }
1479                    self.update_window_edited(cx);
1480                }
1481            }
1482        } else {
1483            error!("pane {} not found", pane_id);
1484        }
1485    }
1486
1487    pub fn split_pane(
1488        &mut self,
1489        pane: ViewHandle<Pane>,
1490        direction: SplitDirection,
1491        cx: &mut ViewContext<Self>,
1492    ) -> ViewHandle<Pane> {
1493        let new_pane = self.add_pane(cx);
1494        self.activate_pane(new_pane.clone(), cx);
1495        if let Some(item) = pane.read(cx).active_item() {
1496            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1497                Pane::add_item(self, new_pane.clone(), clone, true, true, cx);
1498            }
1499        }
1500        self.center.split(&pane, &new_pane, direction).unwrap();
1501        cx.notify();
1502        new_pane
1503    }
1504
1505    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1506        if self.center.remove(&pane).unwrap() {
1507            self.panes.retain(|p| p != &pane);
1508            self.activate_pane(self.panes.last().unwrap().clone(), cx);
1509            self.unfollow(&pane, cx);
1510            self.last_leaders_by_pane.remove(&pane.downgrade());
1511            cx.notify();
1512        } else {
1513            self.active_item_path_changed(cx);
1514        }
1515    }
1516
1517    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1518        &self.panes
1519    }
1520
1521    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1522        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1523    }
1524
1525    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1526        &self.active_pane
1527    }
1528
1529    fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1530        if let Some(remote_id) = remote_id {
1531            self.remote_entity_subscription =
1532                Some(self.client.add_view_for_remote_entity(remote_id, cx));
1533        } else {
1534            self.remote_entity_subscription.take();
1535        }
1536    }
1537
1538    fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1539        self.leader_state.followers.remove(&peer_id);
1540        if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1541            for state in states_by_pane.into_values() {
1542                for item in state.items_by_leader_view_id.into_values() {
1543                    if let FollowerItem::Loaded(item) = item {
1544                        item.set_leader_replica_id(None, cx);
1545                    }
1546                }
1547            }
1548        }
1549        cx.notify();
1550    }
1551
1552    pub fn toggle_follow(
1553        &mut self,
1554        ToggleFollow(leader_id): &ToggleFollow,
1555        cx: &mut ViewContext<Self>,
1556    ) -> Option<Task<Result<()>>> {
1557        let leader_id = *leader_id;
1558        let pane = self.active_pane().clone();
1559
1560        if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1561            if leader_id == prev_leader_id {
1562                return None;
1563            }
1564        }
1565
1566        self.last_leaders_by_pane
1567            .insert(pane.downgrade(), leader_id);
1568        self.follower_states_by_leader
1569            .entry(leader_id)
1570            .or_default()
1571            .insert(pane.clone(), Default::default());
1572        cx.notify();
1573
1574        let project_id = self.project.read(cx).remote_id()?;
1575        let request = self.client.request(proto::Follow {
1576            project_id,
1577            leader_id: leader_id.0,
1578        });
1579        Some(cx.spawn_weak(|this, mut cx| async move {
1580            let response = request.await?;
1581            if let Some(this) = this.upgrade(&cx) {
1582                this.update(&mut cx, |this, _| {
1583                    let state = this
1584                        .follower_states_by_leader
1585                        .get_mut(&leader_id)
1586                        .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1587                        .ok_or_else(|| anyhow!("following interrupted"))?;
1588                    state.active_view_id = response.active_view_id;
1589                    Ok::<_, anyhow::Error>(())
1590                })?;
1591                Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1592                    .await?;
1593            }
1594            Ok(())
1595        }))
1596    }
1597
1598    pub fn follow_next_collaborator(
1599        &mut self,
1600        _: &FollowNextCollaborator,
1601        cx: &mut ViewContext<Self>,
1602    ) -> Option<Task<Result<()>>> {
1603        let collaborators = self.project.read(cx).collaborators();
1604        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1605            let mut collaborators = collaborators.keys().copied();
1606            while let Some(peer_id) = collaborators.next() {
1607                if peer_id == leader_id {
1608                    break;
1609                }
1610            }
1611            collaborators.next()
1612        } else if let Some(last_leader_id) =
1613            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1614        {
1615            if collaborators.contains_key(last_leader_id) {
1616                Some(*last_leader_id)
1617            } else {
1618                None
1619            }
1620        } else {
1621            None
1622        };
1623
1624        next_leader_id
1625            .or_else(|| collaborators.keys().copied().next())
1626            .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1627    }
1628
1629    pub fn unfollow(
1630        &mut self,
1631        pane: &ViewHandle<Pane>,
1632        cx: &mut ViewContext<Self>,
1633    ) -> Option<PeerId> {
1634        for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1635            let leader_id = *leader_id;
1636            if let Some(state) = states_by_pane.remove(&pane) {
1637                for (_, item) in state.items_by_leader_view_id {
1638                    if let FollowerItem::Loaded(item) = item {
1639                        item.set_leader_replica_id(None, cx);
1640                    }
1641                }
1642
1643                if states_by_pane.is_empty() {
1644                    self.follower_states_by_leader.remove(&leader_id);
1645                    if let Some(project_id) = self.project.read(cx).remote_id() {
1646                        self.client
1647                            .send(proto::Unfollow {
1648                                project_id,
1649                                leader_id: leader_id.0,
1650                            })
1651                            .log_err();
1652                    }
1653                }
1654
1655                cx.notify();
1656                return Some(leader_id);
1657            }
1658        }
1659        None
1660    }
1661
1662    fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1663        let theme = &cx.global::<Settings>().theme;
1664        match &*self.client.status().borrow() {
1665            client::Status::ConnectionError
1666            | client::Status::ConnectionLost
1667            | client::Status::Reauthenticating
1668            | client::Status::Reconnecting { .. }
1669            | client::Status::ReconnectionError { .. } => Some(
1670                Container::new(
1671                    Align::new(
1672                        ConstrainedBox::new(
1673                            Svg::new("icons/offline-14.svg")
1674                                .with_color(theme.workspace.titlebar.offline_icon.color)
1675                                .boxed(),
1676                        )
1677                        .with_width(theme.workspace.titlebar.offline_icon.width)
1678                        .boxed(),
1679                    )
1680                    .boxed(),
1681                )
1682                .with_style(theme.workspace.titlebar.offline_icon.container)
1683                .boxed(),
1684            ),
1685            client::Status::UpgradeRequired => Some(
1686                Label::new(
1687                    "Please update Zed to collaborate".to_string(),
1688                    theme.workspace.titlebar.outdated_warning.text.clone(),
1689                )
1690                .contained()
1691                .with_style(theme.workspace.titlebar.outdated_warning.container)
1692                .aligned()
1693                .boxed(),
1694            ),
1695            _ => None,
1696        }
1697    }
1698
1699    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1700        let project = &self.project.read(cx);
1701        let replica_id = project.replica_id();
1702        let mut worktree_root_names = String::new();
1703        for (i, name) in project.worktree_root_names(cx).enumerate() {
1704            if i > 0 {
1705                worktree_root_names.push_str(", ");
1706            }
1707            worktree_root_names.push_str(name);
1708        }
1709
1710        ConstrainedBox::new(
1711            Container::new(
1712                Stack::new()
1713                    .with_child(
1714                        Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
1715                            .aligned()
1716                            .left()
1717                            .boxed(),
1718                    )
1719                    .with_child(
1720                        Align::new(
1721                            Flex::row()
1722                                .with_children(self.render_collaborators(theme, cx))
1723                                .with_children(self.render_current_user(
1724                                    self.user_store.read(cx).current_user().as_ref(),
1725                                    replica_id,
1726                                    theme,
1727                                    cx,
1728                                ))
1729                                .with_children(self.render_connection_status(cx))
1730                                .boxed(),
1731                        )
1732                        .right()
1733                        .boxed(),
1734                    )
1735                    .boxed(),
1736            )
1737            .with_style(theme.workspace.titlebar.container)
1738            .boxed(),
1739        )
1740        .with_height(theme.workspace.titlebar.height)
1741        .named("titlebar")
1742    }
1743
1744    fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
1745        let active_entry = self.active_project_path(cx);
1746        self.project
1747            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1748        self.update_window_title(cx);
1749    }
1750
1751    fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
1752        let mut title = String::new();
1753        let project = self.project().read(cx);
1754        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
1755            let filename = path
1756                .path
1757                .file_name()
1758                .map(|s| s.to_string_lossy())
1759                .or_else(|| {
1760                    Some(Cow::Borrowed(
1761                        project
1762                            .worktree_for_id(path.worktree_id, cx)?
1763                            .read(cx)
1764                            .root_name(),
1765                    ))
1766                });
1767            if let Some(filename) = filename {
1768                title.push_str(filename.as_ref());
1769                title.push_str("");
1770            }
1771        }
1772        for (i, name) in project.worktree_root_names(cx).enumerate() {
1773            if i > 0 {
1774                title.push_str(", ");
1775            }
1776            title.push_str(name);
1777        }
1778        if title.is_empty() {
1779            title = "empty project".to_string();
1780        }
1781        cx.set_window_title(&title);
1782    }
1783
1784    fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
1785        let is_edited = self
1786            .items(cx)
1787            .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
1788        if is_edited != self.window_edited {
1789            self.window_edited = is_edited;
1790            cx.set_window_edited(self.window_edited)
1791        }
1792    }
1793
1794    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1795        let mut collaborators = self
1796            .project
1797            .read(cx)
1798            .collaborators()
1799            .values()
1800            .cloned()
1801            .collect::<Vec<_>>();
1802        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1803        collaborators
1804            .into_iter()
1805            .filter_map(|collaborator| {
1806                Some(self.render_avatar(
1807                    collaborator.user.avatar.clone()?,
1808                    collaborator.replica_id,
1809                    Some((collaborator.peer_id, &collaborator.user.github_login)),
1810                    theme,
1811                    cx,
1812                ))
1813            })
1814            .collect()
1815    }
1816
1817    fn render_current_user(
1818        &self,
1819        user: Option<&Arc<User>>,
1820        replica_id: ReplicaId,
1821        theme: &Theme,
1822        cx: &mut RenderContext<Self>,
1823    ) -> Option<ElementBox> {
1824        let status = *self.client.status().borrow();
1825        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1826            Some(self.render_avatar(avatar, replica_id, None, theme, cx))
1827        } else if matches!(status, client::Status::UpgradeRequired) {
1828            None
1829        } else {
1830            Some(
1831                MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1832                    let style = theme
1833                        .workspace
1834                        .titlebar
1835                        .sign_in_prompt
1836                        .style_for(state, false);
1837                    Label::new("Sign in".to_string(), style.text.clone())
1838                        .contained()
1839                        .with_style(style.container)
1840                        .boxed()
1841                })
1842                .on_click(|_, _, cx| cx.dispatch_action(Authenticate))
1843                .with_cursor_style(CursorStyle::PointingHand)
1844                .aligned()
1845                .boxed(),
1846            )
1847        }
1848    }
1849
1850    fn render_avatar(
1851        &self,
1852        avatar: Arc<ImageData>,
1853        replica_id: ReplicaId,
1854        peer: Option<(PeerId, &str)>,
1855        theme: &Theme,
1856        cx: &mut RenderContext<Self>,
1857    ) -> ElementBox {
1858        let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1859        let is_followed = peer.map_or(false, |(peer_id, _)| {
1860            self.follower_states_by_leader.contains_key(&peer_id)
1861        });
1862        let mut avatar_style = theme.workspace.titlebar.avatar;
1863        if is_followed {
1864            avatar_style.border = Border::all(1.0, replica_color);
1865        }
1866        let content = Stack::new()
1867            .with_child(
1868                Image::new(avatar)
1869                    .with_style(avatar_style)
1870                    .constrained()
1871                    .with_width(theme.workspace.titlebar.avatar_width)
1872                    .aligned()
1873                    .boxed(),
1874            )
1875            .with_child(
1876                AvatarRibbon::new(replica_color)
1877                    .constrained()
1878                    .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1879                    .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1880                    .aligned()
1881                    .bottom()
1882                    .boxed(),
1883            )
1884            .constrained()
1885            .with_width(theme.workspace.titlebar.avatar_width)
1886            .contained()
1887            .with_margin_left(theme.workspace.titlebar.avatar_margin)
1888            .boxed();
1889
1890        if let Some((peer_id, peer_github_login)) = peer {
1891            MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1892                .with_cursor_style(CursorStyle::PointingHand)
1893                .on_click(move |_, _, cx| cx.dispatch_action(ToggleFollow(peer_id)))
1894                .with_tooltip::<ToggleFollow, _>(
1895                    peer_id.0 as usize,
1896                    if is_followed {
1897                        format!("Unfollow {}", peer_github_login)
1898                    } else {
1899                        format!("Follow {}", peer_github_login)
1900                    },
1901                    Some(Box::new(FollowNextCollaborator)),
1902                    theme.tooltip.clone(),
1903                    cx,
1904                )
1905                .boxed()
1906        } else {
1907            content
1908        }
1909    }
1910
1911    fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1912        if self.project.read(cx).is_read_only() {
1913            let theme = &cx.global::<Settings>().theme;
1914            Some(
1915                EventHandler::new(
1916                    Label::new(
1917                        "Your connection to the remote project has been lost.".to_string(),
1918                        theme.workspace.disconnected_overlay.text.clone(),
1919                    )
1920                    .aligned()
1921                    .contained()
1922                    .with_style(theme.workspace.disconnected_overlay.container)
1923                    .boxed(),
1924                )
1925                .capture_all::<Self>(0)
1926                .boxed(),
1927            )
1928        } else {
1929            None
1930        }
1931    }
1932
1933    fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
1934        if self.notifications.is_empty() {
1935            None
1936        } else {
1937            Some(
1938                Flex::column()
1939                    .with_children(self.notifications.iter().map(|(_, _, notification)| {
1940                        ChildView::new(notification.as_ref())
1941                            .contained()
1942                            .with_style(theme.notification)
1943                            .boxed()
1944                    }))
1945                    .constrained()
1946                    .with_width(theme.notifications.width)
1947                    .contained()
1948                    .with_style(theme.notifications.container)
1949                    .aligned()
1950                    .bottom()
1951                    .right()
1952                    .boxed(),
1953            )
1954        }
1955    }
1956
1957    // RPC handlers
1958
1959    async fn handle_follow(
1960        this: ViewHandle<Self>,
1961        envelope: TypedEnvelope<proto::Follow>,
1962        _: Arc<Client>,
1963        mut cx: AsyncAppContext,
1964    ) -> Result<proto::FollowResponse> {
1965        this.update(&mut cx, |this, cx| {
1966            this.leader_state
1967                .followers
1968                .insert(envelope.original_sender_id()?);
1969
1970            let active_view_id = this
1971                .active_item(cx)
1972                .and_then(|i| i.to_followable_item_handle(cx))
1973                .map(|i| i.id() as u64);
1974            Ok(proto::FollowResponse {
1975                active_view_id,
1976                views: this
1977                    .panes()
1978                    .iter()
1979                    .flat_map(|pane| {
1980                        let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1981                        pane.read(cx).items().filter_map({
1982                            let cx = &cx;
1983                            move |item| {
1984                                let id = item.id() as u64;
1985                                let item = item.to_followable_item_handle(cx)?;
1986                                let variant = item.to_state_proto(cx)?;
1987                                Some(proto::View {
1988                                    id,
1989                                    leader_id,
1990                                    variant: Some(variant),
1991                                })
1992                            }
1993                        })
1994                    })
1995                    .collect(),
1996            })
1997        })
1998    }
1999
2000    async fn handle_unfollow(
2001        this: ViewHandle<Self>,
2002        envelope: TypedEnvelope<proto::Unfollow>,
2003        _: Arc<Client>,
2004        mut cx: AsyncAppContext,
2005    ) -> Result<()> {
2006        this.update(&mut cx, |this, _| {
2007            this.leader_state
2008                .followers
2009                .remove(&envelope.original_sender_id()?);
2010            Ok(())
2011        })
2012    }
2013
2014    async fn handle_update_followers(
2015        this: ViewHandle<Self>,
2016        envelope: TypedEnvelope<proto::UpdateFollowers>,
2017        _: Arc<Client>,
2018        mut cx: AsyncAppContext,
2019    ) -> Result<()> {
2020        let leader_id = envelope.original_sender_id()?;
2021        match envelope
2022            .payload
2023            .variant
2024            .ok_or_else(|| anyhow!("invalid update"))?
2025        {
2026            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2027                this.update(&mut cx, |this, cx| {
2028                    this.update_leader_state(leader_id, cx, |state, _| {
2029                        state.active_view_id = update_active_view.id;
2030                    });
2031                    Ok::<_, anyhow::Error>(())
2032                })
2033            }
2034            proto::update_followers::Variant::UpdateView(update_view) => {
2035                this.update(&mut cx, |this, cx| {
2036                    let variant = update_view
2037                        .variant
2038                        .ok_or_else(|| anyhow!("missing update view variant"))?;
2039                    this.update_leader_state(leader_id, cx, |state, cx| {
2040                        let variant = variant.clone();
2041                        match state
2042                            .items_by_leader_view_id
2043                            .entry(update_view.id)
2044                            .or_insert(FollowerItem::Loading(Vec::new()))
2045                        {
2046                            FollowerItem::Loaded(item) => {
2047                                item.apply_update_proto(variant, cx).log_err();
2048                            }
2049                            FollowerItem::Loading(updates) => updates.push(variant),
2050                        }
2051                    });
2052                    Ok(())
2053                })
2054            }
2055            proto::update_followers::Variant::CreateView(view) => {
2056                let panes = this.read_with(&cx, |this, _| {
2057                    this.follower_states_by_leader
2058                        .get(&leader_id)
2059                        .into_iter()
2060                        .flat_map(|states_by_pane| states_by_pane.keys())
2061                        .cloned()
2062                        .collect()
2063                });
2064                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
2065                    .await?;
2066                Ok(())
2067            }
2068        }
2069        .log_err();
2070
2071        Ok(())
2072    }
2073
2074    async fn add_views_from_leader(
2075        this: ViewHandle<Self>,
2076        leader_id: PeerId,
2077        panes: Vec<ViewHandle<Pane>>,
2078        views: Vec<proto::View>,
2079        cx: &mut AsyncAppContext,
2080    ) -> Result<()> {
2081        let project = this.read_with(cx, |this, _| this.project.clone());
2082        let replica_id = project
2083            .read_with(cx, |project, _| {
2084                project
2085                    .collaborators()
2086                    .get(&leader_id)
2087                    .map(|c| c.replica_id)
2088            })
2089            .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
2090
2091        let item_builders = cx.update(|cx| {
2092            cx.default_global::<FollowableItemBuilders>()
2093                .values()
2094                .map(|b| b.0)
2095                .collect::<Vec<_>>()
2096                .clone()
2097        });
2098
2099        let mut item_tasks_by_pane = HashMap::default();
2100        for pane in panes {
2101            let mut item_tasks = Vec::new();
2102            let mut leader_view_ids = Vec::new();
2103            for view in &views {
2104                let mut variant = view.variant.clone();
2105                if variant.is_none() {
2106                    Err(anyhow!("missing variant"))?;
2107                }
2108                for build_item in &item_builders {
2109                    let task =
2110                        cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
2111                    if let Some(task) = task {
2112                        item_tasks.push(task);
2113                        leader_view_ids.push(view.id);
2114                        break;
2115                    } else {
2116                        assert!(variant.is_some());
2117                    }
2118                }
2119            }
2120
2121            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2122        }
2123
2124        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2125            let items = futures::future::try_join_all(item_tasks).await?;
2126            this.update(cx, |this, cx| {
2127                let state = this
2128                    .follower_states_by_leader
2129                    .get_mut(&leader_id)?
2130                    .get_mut(&pane)?;
2131
2132                for (id, item) in leader_view_ids.into_iter().zip(items) {
2133                    item.set_leader_replica_id(Some(replica_id), cx);
2134                    match state.items_by_leader_view_id.entry(id) {
2135                        hash_map::Entry::Occupied(e) => {
2136                            let e = e.into_mut();
2137                            if let FollowerItem::Loading(updates) = e {
2138                                for update in updates.drain(..) {
2139                                    item.apply_update_proto(update, cx)
2140                                        .context("failed to apply view update")
2141                                        .log_err();
2142                                }
2143                            }
2144                            *e = FollowerItem::Loaded(item);
2145                        }
2146                        hash_map::Entry::Vacant(e) => {
2147                            e.insert(FollowerItem::Loaded(item));
2148                        }
2149                    }
2150                }
2151
2152                Some(())
2153            });
2154        }
2155        this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
2156
2157        Ok(())
2158    }
2159
2160    fn update_followers(
2161        &self,
2162        update: proto::update_followers::Variant,
2163        cx: &AppContext,
2164    ) -> Option<()> {
2165        let project_id = self.project.read(cx).remote_id()?;
2166        if !self.leader_state.followers.is_empty() {
2167            self.client
2168                .send(proto::UpdateFollowers {
2169                    project_id,
2170                    follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
2171                    variant: Some(update),
2172                })
2173                .log_err();
2174        }
2175        None
2176    }
2177
2178    pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
2179        self.follower_states_by_leader
2180            .iter()
2181            .find_map(|(leader_id, state)| {
2182                if state.contains_key(pane) {
2183                    Some(*leader_id)
2184                } else {
2185                    None
2186                }
2187            })
2188    }
2189
2190    fn update_leader_state(
2191        &mut self,
2192        leader_id: PeerId,
2193        cx: &mut ViewContext<Self>,
2194        mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
2195    ) {
2196        for (_, state) in self
2197            .follower_states_by_leader
2198            .get_mut(&leader_id)
2199            .into_iter()
2200            .flatten()
2201        {
2202            update_fn(state, cx);
2203        }
2204        self.leader_updated(leader_id, cx);
2205    }
2206
2207    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2208        let mut items_to_add = Vec::new();
2209        for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2210            if let Some(active_item) = state
2211                .active_view_id
2212                .and_then(|id| state.items_by_leader_view_id.get(&id))
2213            {
2214                if let FollowerItem::Loaded(item) = active_item {
2215                    items_to_add.push((pane.clone(), item.boxed_clone()));
2216                }
2217            }
2218        }
2219
2220        for (pane, item) in items_to_add {
2221            Pane::add_item(self, pane.clone(), item.boxed_clone(), false, false, cx);
2222            if pane == self.active_pane {
2223                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2224            }
2225            cx.notify();
2226        }
2227        None
2228    }
2229}
2230
2231impl Entity for Workspace {
2232    type Event = Event;
2233}
2234
2235impl View for Workspace {
2236    fn ui_name() -> &'static str {
2237        "Workspace"
2238    }
2239
2240    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2241        let theme = cx.global::<Settings>().theme.clone();
2242        Stack::new()
2243            .with_child(
2244                Flex::column()
2245                    .with_child(self.render_titlebar(&theme, cx))
2246                    .with_child(
2247                        Stack::new()
2248                            .with_child({
2249                                Flex::row()
2250                                    .with_children(
2251                                        if self.left_sidebar.read(cx).active_item().is_some() {
2252                                            Some(
2253                                                ChildView::new(&self.left_sidebar)
2254                                                    .flex(0.8, false)
2255                                                    .boxed(),
2256                                            )
2257                                        } else {
2258                                            None
2259                                        },
2260                                    )
2261                                    .with_child(
2262                                        FlexItem::new(self.center.render(
2263                                            &theme,
2264                                            &self.follower_states_by_leader,
2265                                            self.project.read(cx).collaborators(),
2266                                        ))
2267                                        .flex(1., true)
2268                                        .boxed(),
2269                                    )
2270                                    .with_children(
2271                                        if self.right_sidebar.read(cx).active_item().is_some() {
2272                                            Some(
2273                                                ChildView::new(&self.right_sidebar)
2274                                                    .flex(0.8, false)
2275                                                    .boxed(),
2276                                            )
2277                                        } else {
2278                                            None
2279                                        },
2280                                    )
2281                                    .boxed()
2282                            })
2283                            .with_children(self.modal.as_ref().map(|m| {
2284                                ChildView::new(m)
2285                                    .contained()
2286                                    .with_style(theme.workspace.modal)
2287                                    .aligned()
2288                                    .top()
2289                                    .boxed()
2290                            }))
2291                            .with_children(self.render_notifications(&theme.workspace))
2292                            .flex(1.0, true)
2293                            .boxed(),
2294                    )
2295                    .with_child(ChildView::new(&self.status_bar).boxed())
2296                    .contained()
2297                    .with_background_color(theme.workspace.background)
2298                    .boxed(),
2299            )
2300            .with_children(self.render_disconnected_overlay(cx))
2301            .named("workspace")
2302    }
2303
2304    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2305        cx.focus(&self.active_pane);
2306    }
2307}
2308
2309pub trait WorkspaceHandle {
2310    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2311}
2312
2313impl WorkspaceHandle for ViewHandle<Workspace> {
2314    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2315        self.read(cx)
2316            .worktrees(cx)
2317            .flat_map(|worktree| {
2318                let worktree_id = worktree.read(cx).id();
2319                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2320                    worktree_id,
2321                    path: f.path.clone(),
2322                })
2323            })
2324            .collect::<Vec<_>>()
2325    }
2326}
2327
2328pub struct AvatarRibbon {
2329    color: Color,
2330}
2331
2332impl AvatarRibbon {
2333    pub fn new(color: Color) -> AvatarRibbon {
2334        AvatarRibbon { color }
2335    }
2336}
2337
2338impl Element for AvatarRibbon {
2339    type LayoutState = ();
2340
2341    type PaintState = ();
2342
2343    fn layout(
2344        &mut self,
2345        constraint: gpui::SizeConstraint,
2346        _: &mut gpui::LayoutContext,
2347    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2348        (constraint.max, ())
2349    }
2350
2351    fn paint(
2352        &mut self,
2353        bounds: gpui::geometry::rect::RectF,
2354        _: gpui::geometry::rect::RectF,
2355        _: &mut Self::LayoutState,
2356        cx: &mut gpui::PaintContext,
2357    ) -> Self::PaintState {
2358        let mut path = PathBuilder::new();
2359        path.reset(bounds.lower_left());
2360        path.curve_to(
2361            bounds.origin() + vec2f(bounds.height(), 0.),
2362            bounds.origin(),
2363        );
2364        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2365        path.curve_to(bounds.lower_right(), bounds.upper_right());
2366        path.line_to(bounds.lower_left());
2367        cx.scene.push_path(path.build(self.color, None));
2368    }
2369
2370    fn dispatch_event(
2371        &mut self,
2372        _: &gpui::Event,
2373        _: RectF,
2374        _: RectF,
2375        _: &mut Self::LayoutState,
2376        _: &mut Self::PaintState,
2377        _: &mut gpui::EventContext,
2378    ) -> bool {
2379        false
2380    }
2381
2382    fn debug(
2383        &self,
2384        bounds: gpui::geometry::rect::RectF,
2385        _: &Self::LayoutState,
2386        _: &Self::PaintState,
2387        _: &gpui::DebugContext,
2388    ) -> gpui::json::Value {
2389        json::json!({
2390            "type": "AvatarRibbon",
2391            "bounds": bounds.to_json(),
2392            "color": self.color.to_json(),
2393        })
2394    }
2395}
2396
2397impl std::fmt::Debug for OpenPaths {
2398    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2399        f.debug_struct("OpenPaths")
2400            .field("paths", &self.paths)
2401            .finish()
2402    }
2403}
2404
2405fn open(_: &Open, cx: &mut MutableAppContext) {
2406    let mut paths = cx.prompt_for_paths(PathPromptOptions {
2407        files: true,
2408        directories: true,
2409        multiple: true,
2410    });
2411    cx.spawn(|mut cx| async move {
2412        if let Some(paths) = paths.recv().await.flatten() {
2413            cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2414        }
2415    })
2416    .detach();
2417}
2418
2419pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2420
2421pub fn activate_workspace_for_project(
2422    cx: &mut MutableAppContext,
2423    predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2424) -> Option<ViewHandle<Workspace>> {
2425    for window_id in cx.window_ids().collect::<Vec<_>>() {
2426        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2427            let project = workspace_handle.read(cx).project.clone();
2428            if project.update(cx, &predicate) {
2429                cx.activate_window(window_id);
2430                return Some(workspace_handle);
2431            }
2432        }
2433    }
2434    None
2435}
2436
2437pub fn open_paths(
2438    abs_paths: &[PathBuf],
2439    app_state: &Arc<AppState>,
2440    cx: &mut MutableAppContext,
2441) -> Task<(
2442    ViewHandle<Workspace>,
2443    Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2444)> {
2445    log::info!("open paths {:?}", abs_paths);
2446
2447    // Open paths in existing workspace if possible
2448    let existing =
2449        activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2450
2451    let app_state = app_state.clone();
2452    let abs_paths = abs_paths.to_vec();
2453    cx.spawn(|mut cx| async move {
2454        let mut new_project = None;
2455        let workspace = if let Some(existing) = existing {
2456            existing
2457        } else {
2458            let contains_directory =
2459                futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2460                    .await
2461                    .contains(&false);
2462
2463            cx.add_window((app_state.build_window_options)(), |cx| {
2464                let project = Project::local(
2465                    false,
2466                    app_state.client.clone(),
2467                    app_state.user_store.clone(),
2468                    app_state.project_store.clone(),
2469                    app_state.languages.clone(),
2470                    app_state.fs.clone(),
2471                    cx,
2472                );
2473                new_project = Some(project.clone());
2474                let mut workspace = Workspace::new(project, cx);
2475                (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2476                if contains_directory {
2477                    workspace.toggle_sidebar_item(
2478                        &ToggleSidebarItem {
2479                            side: Side::Left,
2480                            item_index: 0,
2481                        },
2482                        cx,
2483                    );
2484                }
2485                workspace
2486            })
2487            .1
2488        };
2489
2490        let items = workspace
2491            .update(&mut cx, |workspace, cx| {
2492                workspace.open_paths(abs_paths, true, cx)
2493            })
2494            .await;
2495
2496        if let Some(project) = new_project {
2497            project
2498                .update(&mut cx, |project, cx| project.restore_state(cx))
2499                .await
2500                .log_err();
2501        }
2502
2503        (workspace, items)
2504    })
2505}
2506
2507pub fn join_project(
2508    contact: Arc<Contact>,
2509    project_index: usize,
2510    app_state: &Arc<AppState>,
2511    cx: &mut MutableAppContext,
2512) {
2513    let project_id = contact.projects[project_index].id;
2514
2515    for window_id in cx.window_ids().collect::<Vec<_>>() {
2516        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2517            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2518                cx.activate_window(window_id);
2519                return;
2520            }
2521        }
2522    }
2523
2524    cx.add_window((app_state.build_window_options)(), |cx| {
2525        WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2526    });
2527}
2528
2529fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2530    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2531        let mut workspace = Workspace::new(
2532            Project::local(
2533                false,
2534                app_state.client.clone(),
2535                app_state.user_store.clone(),
2536                app_state.project_store.clone(),
2537                app_state.languages.clone(),
2538                app_state.fs.clone(),
2539                cx,
2540            ),
2541            cx,
2542        );
2543        (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2544        workspace
2545    });
2546    cx.dispatch_action(window_id, vec![workspace.id()], &NewFile);
2547}
2548
2549#[cfg(test)]
2550mod tests {
2551    use super::*;
2552    use gpui::{ModelHandle, TestAppContext, ViewContext};
2553    use project::{FakeFs, Project, ProjectEntryId};
2554    use serde_json::json;
2555
2556    #[gpui::test]
2557    async fn test_tracking_active_path(cx: &mut TestAppContext) {
2558        cx.foreground().forbid_parking();
2559        Settings::test_async(cx);
2560        let fs = FakeFs::new(cx.background());
2561        fs.insert_tree(
2562            "/root1",
2563            json!({
2564                "one.txt": "",
2565                "two.txt": "",
2566            }),
2567        )
2568        .await;
2569        fs.insert_tree(
2570            "/root2",
2571            json!({
2572                "three.txt": "",
2573            }),
2574        )
2575        .await;
2576
2577        let project = Project::test(fs, ["root1".as_ref()], cx).await;
2578        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2579        let worktree_id = project.read_with(cx, |project, cx| {
2580            project.worktrees(cx).next().unwrap().read(cx).id()
2581        });
2582
2583        let item1 = cx.add_view(window_id, |_| {
2584            let mut item = TestItem::new();
2585            item.project_path = Some((worktree_id, "one.txt").into());
2586            item
2587        });
2588        let item2 = cx.add_view(window_id, |_| {
2589            let mut item = TestItem::new();
2590            item.project_path = Some((worktree_id, "two.txt").into());
2591            item
2592        });
2593
2594        // Add an item to an empty pane
2595        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
2596        project.read_with(cx, |project, cx| {
2597            assert_eq!(
2598                project.active_entry(),
2599                project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2600            );
2601        });
2602        assert_eq!(
2603            cx.current_window_title(window_id).as_deref(),
2604            Some("one.txt — root1")
2605        );
2606
2607        // Add a second item to a non-empty pane
2608        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
2609        assert_eq!(
2610            cx.current_window_title(window_id).as_deref(),
2611            Some("two.txt — root1")
2612        );
2613        project.read_with(cx, |project, cx| {
2614            assert_eq!(
2615                project.active_entry(),
2616                project.entry_for_path(&(worktree_id, "two.txt").into(), cx)
2617            );
2618        });
2619
2620        // Close the active item
2621        workspace
2622            .update(cx, |workspace, cx| {
2623                Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
2624            })
2625            .await
2626            .unwrap();
2627        assert_eq!(
2628            cx.current_window_title(window_id).as_deref(),
2629            Some("one.txt — root1")
2630        );
2631        project.read_with(cx, |project, cx| {
2632            assert_eq!(
2633                project.active_entry(),
2634                project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2635            );
2636        });
2637
2638        // Add a project folder
2639        project
2640            .update(cx, |project, cx| {
2641                project.find_or_create_local_worktree("/root2", true, cx)
2642            })
2643            .await
2644            .unwrap();
2645        assert_eq!(
2646            cx.current_window_title(window_id).as_deref(),
2647            Some("one.txt — root1, root2")
2648        );
2649
2650        // Remove a project folder
2651        project.update(cx, |project, cx| {
2652            project.remove_worktree(worktree_id, cx);
2653        });
2654        assert_eq!(
2655            cx.current_window_title(window_id).as_deref(),
2656            Some("one.txt — root2")
2657        );
2658    }
2659
2660    #[gpui::test]
2661    async fn test_close_window(cx: &mut TestAppContext) {
2662        cx.foreground().forbid_parking();
2663        Settings::test_async(cx);
2664        let fs = FakeFs::new(cx.background());
2665        fs.insert_tree("/root", json!({ "one": "" })).await;
2666
2667        let project = Project::test(fs, ["root".as_ref()], cx).await;
2668        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2669
2670        // When there are no dirty items, there's nothing to do.
2671        let item1 = cx.add_view(window_id, |_| TestItem::new());
2672        workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
2673        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2674        assert_eq!(task.await.unwrap(), true);
2675
2676        // When there are dirty untitled items, prompt to save each one. If the user
2677        // cancels any prompt, then abort.
2678        let item2 = cx.add_view(window_id, |_| {
2679            let mut item = TestItem::new();
2680            item.is_dirty = true;
2681            item
2682        });
2683        let item3 = cx.add_view(window_id, |_| {
2684            let mut item = TestItem::new();
2685            item.is_dirty = true;
2686            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2687            item
2688        });
2689        workspace.update(cx, |w, cx| {
2690            w.add_item(Box::new(item2.clone()), cx);
2691            w.add_item(Box::new(item3.clone()), cx);
2692        });
2693        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2694        cx.foreground().run_until_parked();
2695        cx.simulate_prompt_answer(window_id, 2 /* cancel */);
2696        cx.foreground().run_until_parked();
2697        assert!(!cx.has_pending_prompt(window_id));
2698        assert_eq!(task.await.unwrap(), false);
2699    }
2700
2701    #[gpui::test]
2702    async fn test_close_pane_items(cx: &mut TestAppContext) {
2703        cx.foreground().forbid_parking();
2704        Settings::test_async(cx);
2705        let fs = FakeFs::new(cx.background());
2706
2707        let project = Project::test(fs, None, cx).await;
2708        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
2709
2710        let item1 = cx.add_view(window_id, |_| {
2711            let mut item = TestItem::new();
2712            item.is_dirty = true;
2713            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2714            item
2715        });
2716        let item2 = cx.add_view(window_id, |_| {
2717            let mut item = TestItem::new();
2718            item.is_dirty = true;
2719            item.has_conflict = true;
2720            item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
2721            item
2722        });
2723        let item3 = cx.add_view(window_id, |_| {
2724            let mut item = TestItem::new();
2725            item.is_dirty = true;
2726            item.has_conflict = true;
2727            item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
2728            item
2729        });
2730        let item4 = cx.add_view(window_id, |_| {
2731            let mut item = TestItem::new();
2732            item.is_dirty = true;
2733            item
2734        });
2735        let pane = workspace.update(cx, |workspace, cx| {
2736            workspace.add_item(Box::new(item1.clone()), cx);
2737            workspace.add_item(Box::new(item2.clone()), cx);
2738            workspace.add_item(Box::new(item3.clone()), cx);
2739            workspace.add_item(Box::new(item4.clone()), cx);
2740            workspace.active_pane().clone()
2741        });
2742
2743        let close_items = workspace.update(cx, |workspace, cx| {
2744            pane.update(cx, |pane, cx| {
2745                pane.activate_item(1, true, true, cx);
2746                assert_eq!(pane.active_item().unwrap().id(), item2.id());
2747            });
2748
2749            let item1_id = item1.id();
2750            let item3_id = item3.id();
2751            let item4_id = item4.id();
2752            Pane::close_items(workspace, pane.clone(), cx, move |id| {
2753                [item1_id, item3_id, item4_id].contains(&id)
2754            })
2755        });
2756
2757        cx.foreground().run_until_parked();
2758        pane.read_with(cx, |pane, _| {
2759            assert_eq!(pane.items().count(), 4);
2760            assert_eq!(pane.active_item().unwrap().id(), item1.id());
2761        });
2762
2763        cx.simulate_prompt_answer(window_id, 0);
2764        cx.foreground().run_until_parked();
2765        pane.read_with(cx, |pane, cx| {
2766            assert_eq!(item1.read(cx).save_count, 1);
2767            assert_eq!(item1.read(cx).save_as_count, 0);
2768            assert_eq!(item1.read(cx).reload_count, 0);
2769            assert_eq!(pane.items().count(), 3);
2770            assert_eq!(pane.active_item().unwrap().id(), item3.id());
2771        });
2772
2773        cx.simulate_prompt_answer(window_id, 1);
2774        cx.foreground().run_until_parked();
2775        pane.read_with(cx, |pane, cx| {
2776            assert_eq!(item3.read(cx).save_count, 0);
2777            assert_eq!(item3.read(cx).save_as_count, 0);
2778            assert_eq!(item3.read(cx).reload_count, 1);
2779            assert_eq!(pane.items().count(), 2);
2780            assert_eq!(pane.active_item().unwrap().id(), item4.id());
2781        });
2782
2783        cx.simulate_prompt_answer(window_id, 0);
2784        cx.foreground().run_until_parked();
2785        cx.simulate_new_path_selection(|_| Some(Default::default()));
2786        close_items.await.unwrap();
2787        pane.read_with(cx, |pane, cx| {
2788            assert_eq!(item4.read(cx).save_count, 0);
2789            assert_eq!(item4.read(cx).save_as_count, 1);
2790            assert_eq!(item4.read(cx).reload_count, 0);
2791            assert_eq!(pane.items().count(), 1);
2792            assert_eq!(pane.active_item().unwrap().id(), item2.id());
2793        });
2794    }
2795
2796    #[gpui::test]
2797    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
2798        cx.foreground().forbid_parking();
2799        Settings::test_async(cx);
2800        let fs = FakeFs::new(cx.background());
2801
2802        let project = Project::test(fs, [], cx).await;
2803        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
2804
2805        // Create several workspace items with single project entries, and two
2806        // workspace items with multiple project entries.
2807        let single_entry_items = (0..=4)
2808            .map(|project_entry_id| {
2809                let mut item = TestItem::new();
2810                item.is_dirty = true;
2811                item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
2812                item.is_singleton = true;
2813                item
2814            })
2815            .collect::<Vec<_>>();
2816        let item_2_3 = {
2817            let mut item = TestItem::new();
2818            item.is_dirty = true;
2819            item.is_singleton = false;
2820            item.project_entry_ids =
2821                vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
2822            item
2823        };
2824        let item_3_4 = {
2825            let mut item = TestItem::new();
2826            item.is_dirty = true;
2827            item.is_singleton = false;
2828            item.project_entry_ids =
2829                vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
2830            item
2831        };
2832
2833        // Create two panes that contain the following project entries:
2834        //   left pane:
2835        //     multi-entry items:   (2, 3)
2836        //     single-entry items:  0, 1, 2, 3, 4
2837        //   right pane:
2838        //     single-entry items:  1
2839        //     multi-entry items:   (3, 4)
2840        let left_pane = workspace.update(cx, |workspace, cx| {
2841            let left_pane = workspace.active_pane().clone();
2842            let right_pane = workspace.split_pane(left_pane.clone(), SplitDirection::Right, cx);
2843
2844            workspace.activate_pane(left_pane.clone(), cx);
2845            workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
2846            for item in &single_entry_items {
2847                workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
2848            }
2849
2850            workspace.activate_pane(right_pane.clone(), cx);
2851            workspace.add_item(Box::new(cx.add_view(|_| single_entry_items[1].clone())), cx);
2852            workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
2853
2854            left_pane
2855        });
2856
2857        // When closing all of the items in the left pane, we should be prompted twice:
2858        // once for project entry 0, and once for project entry 2. After those two
2859        // prompts, the task should complete.
2860        let close = workspace.update(cx, |workspace, cx| {
2861            workspace.activate_pane(left_pane.clone(), cx);
2862            Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
2863        });
2864
2865        cx.foreground().run_until_parked();
2866        left_pane.read_with(cx, |pane, cx| {
2867            assert_eq!(
2868                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
2869                &[ProjectEntryId::from_proto(0)]
2870            );
2871        });
2872        cx.simulate_prompt_answer(window_id, 0);
2873
2874        cx.foreground().run_until_parked();
2875        left_pane.read_with(cx, |pane, cx| {
2876            assert_eq!(
2877                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
2878                &[ProjectEntryId::from_proto(2)]
2879            );
2880        });
2881        cx.simulate_prompt_answer(window_id, 0);
2882
2883        cx.foreground().run_until_parked();
2884        close.await.unwrap();
2885        left_pane.read_with(cx, |pane, _| {
2886            assert_eq!(pane.items().count(), 0);
2887        });
2888    }
2889
2890    #[derive(Clone)]
2891    struct TestItem {
2892        save_count: usize,
2893        save_as_count: usize,
2894        reload_count: usize,
2895        is_dirty: bool,
2896        has_conflict: bool,
2897        project_entry_ids: Vec<ProjectEntryId>,
2898        project_path: Option<ProjectPath>,
2899        is_singleton: bool,
2900    }
2901
2902    impl TestItem {
2903        fn new() -> Self {
2904            Self {
2905                save_count: 0,
2906                save_as_count: 0,
2907                reload_count: 0,
2908                is_dirty: false,
2909                has_conflict: false,
2910                project_entry_ids: Vec::new(),
2911                project_path: None,
2912                is_singleton: true,
2913            }
2914        }
2915    }
2916
2917    impl Entity for TestItem {
2918        type Event = ();
2919    }
2920
2921    impl View for TestItem {
2922        fn ui_name() -> &'static str {
2923            "TestItem"
2924        }
2925
2926        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
2927            Empty::new().boxed()
2928        }
2929    }
2930
2931    impl Item for TestItem {
2932        fn tab_content(&self, _: &theme::Tab, _: &AppContext) -> ElementBox {
2933            Empty::new().boxed()
2934        }
2935
2936        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
2937            self.project_path.clone()
2938        }
2939
2940        fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
2941            self.project_entry_ids.iter().copied().collect()
2942        }
2943
2944        fn is_singleton(&self, _: &AppContext) -> bool {
2945            self.is_singleton
2946        }
2947
2948        fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
2949
2950        fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
2951        where
2952            Self: Sized,
2953        {
2954            Some(self.clone())
2955        }
2956
2957        fn is_dirty(&self, _: &AppContext) -> bool {
2958            self.is_dirty
2959        }
2960
2961        fn has_conflict(&self, _: &AppContext) -> bool {
2962            self.has_conflict
2963        }
2964
2965        fn can_save(&self, _: &AppContext) -> bool {
2966            self.project_entry_ids.len() > 0
2967        }
2968
2969        fn save(
2970            &mut self,
2971            _: ModelHandle<Project>,
2972            _: &mut ViewContext<Self>,
2973        ) -> Task<anyhow::Result<()>> {
2974            self.save_count += 1;
2975            Task::ready(Ok(()))
2976        }
2977
2978        fn save_as(
2979            &mut self,
2980            _: ModelHandle<Project>,
2981            _: std::path::PathBuf,
2982            _: &mut ViewContext<Self>,
2983        ) -> Task<anyhow::Result<()>> {
2984            self.save_as_count += 1;
2985            Task::ready(Ok(()))
2986        }
2987
2988        fn reload(
2989            &mut self,
2990            _: ModelHandle<Project>,
2991            _: &mut ViewContext<Self>,
2992        ) -> Task<anyhow::Result<()>> {
2993            self.reload_count += 1;
2994            Task::ready(Ok(()))
2995        }
2996
2997        fn should_update_tab_on_event(_: &Self::Event) -> bool {
2998            true
2999        }
3000    }
3001}