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    pub fn close(
 911        &mut self,
 912        _: &CloseWindow,
 913        cx: &mut ViewContext<Self>,
 914    ) -> Option<Task<Result<()>>> {
 915        let prepare = self.prepare_to_close(cx);
 916        Some(cx.spawn(|this, mut cx| async move {
 917            if prepare.await? {
 918                this.update(&mut cx, |_, cx| {
 919                    let window_id = cx.window_id();
 920                    cx.remove_window(window_id);
 921                });
 922            }
 923            Ok(())
 924        }))
 925    }
 926
 927    pub fn prepare_to_close(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
 928        self.save_all_internal(true, cx)
 929    }
 930
 931    fn save_all(&mut self, _: &SaveAll, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 932        let save_all = self.save_all_internal(false, cx);
 933        Some(cx.foreground().spawn(async move {
 934            save_all.await?;
 935            Ok(())
 936        }))
 937    }
 938
 939    fn save_all_internal(
 940        &mut self,
 941        should_prompt_to_save: bool,
 942        cx: &mut ViewContext<Self>,
 943    ) -> Task<Result<bool>> {
 944        let dirty_items = self
 945            .panes
 946            .iter()
 947            .flat_map(|pane| {
 948                pane.read(cx).items().filter_map(|item| {
 949                    if item.is_dirty(cx) {
 950                        Some((pane.clone(), item.boxed_clone()))
 951                    } else {
 952                        None
 953                    }
 954                })
 955            })
 956            .collect::<Vec<_>>();
 957
 958        let project = self.project.clone();
 959        cx.spawn_weak(|_, mut cx| async move {
 960            // let mut saved_project_entry_ids = HashSet::default();
 961            for (pane, item) in dirty_items {
 962                let (is_singl, project_entry_ids) =
 963                    cx.read(|cx| (item.is_singleton(cx), item.project_entry_ids(cx)));
 964                if is_singl || !project_entry_ids.is_empty() {
 965                    if let Some(ix) =
 966                        pane.read_with(&cx, |pane, _| pane.index_for_item(item.as_ref()))
 967                    {
 968                        if !Pane::save_item(
 969                            project.clone(),
 970                            &pane,
 971                            ix,
 972                            &item,
 973                            should_prompt_to_save,
 974                            &mut cx,
 975                        )
 976                        .await?
 977                        {
 978                            return Ok(false);
 979                        }
 980                    }
 981                }
 982            }
 983            Ok(true)
 984        })
 985    }
 986
 987    pub fn open_paths(
 988        &mut self,
 989        mut abs_paths: Vec<PathBuf>,
 990        visible: bool,
 991        cx: &mut ViewContext<Self>,
 992    ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
 993        let fs = self.fs.clone();
 994
 995        // Sort the paths to ensure we add worktrees for parents before their children.
 996        abs_paths.sort_unstable();
 997        cx.spawn(|this, mut cx| async move {
 998            let mut entries = Vec::new();
 999            for path in &abs_paths {
1000                entries.push(
1001                    this.update(&mut cx, |this, cx| {
1002                        this.project_path_for_path(path, visible, cx)
1003                    })
1004                    .await
1005                    .log_err(),
1006                );
1007            }
1008
1009            let tasks = abs_paths
1010                .iter()
1011                .cloned()
1012                .zip(entries.into_iter())
1013                .map(|(abs_path, project_path)| {
1014                    let this = this.clone();
1015                    cx.spawn(|mut cx| {
1016                        let fs = fs.clone();
1017                        async move {
1018                            let (_worktree, project_path) = project_path?;
1019                            if fs.is_file(&abs_path).await {
1020                                Some(
1021                                    this.update(&mut cx, |this, cx| {
1022                                        this.open_path(project_path, true, cx)
1023                                    })
1024                                    .await,
1025                                )
1026                            } else {
1027                                None
1028                            }
1029                        }
1030                    })
1031                })
1032                .collect::<Vec<_>>();
1033
1034            futures::future::join_all(tasks).await
1035        })
1036    }
1037
1038    fn add_folder_to_project(&mut self, _: &AddFolderToProject, cx: &mut ViewContext<Self>) {
1039        let mut paths = cx.prompt_for_paths(PathPromptOptions {
1040            files: false,
1041            directories: true,
1042            multiple: true,
1043        });
1044        cx.spawn(|this, mut cx| async move {
1045            if let Some(paths) = paths.recv().await.flatten() {
1046                let results = this
1047                    .update(&mut cx, |this, cx| this.open_paths(paths, true, cx))
1048                    .await;
1049                for result in results {
1050                    if let Some(result) = result {
1051                        result.log_err();
1052                    }
1053                }
1054            }
1055        })
1056        .detach();
1057    }
1058
1059    fn remove_folder_from_project(
1060        &mut self,
1061        RemoveWorktreeFromProject(worktree_id): &RemoveWorktreeFromProject,
1062        cx: &mut ViewContext<Self>,
1063    ) {
1064        self.project
1065            .update(cx, |project, cx| project.remove_worktree(*worktree_id, cx));
1066    }
1067
1068    fn toggle_project_online(&mut self, action: &ToggleProjectOnline, cx: &mut ViewContext<Self>) {
1069        let project = action
1070            .project
1071            .clone()
1072            .unwrap_or_else(|| self.project.clone());
1073        project.update(cx, |project, cx| {
1074            let public = !project.is_online();
1075            project.set_online(public, cx);
1076        });
1077    }
1078
1079    fn project_path_for_path(
1080        &self,
1081        abs_path: &Path,
1082        visible: bool,
1083        cx: &mut ViewContext<Self>,
1084    ) -> Task<Result<(ModelHandle<Worktree>, ProjectPath)>> {
1085        let entry = self.project().update(cx, |project, cx| {
1086            project.find_or_create_local_worktree(abs_path, visible, cx)
1087        });
1088        cx.spawn(|_, cx| async move {
1089            let (worktree, path) = entry.await?;
1090            let worktree_id = worktree.read_with(&cx, |t, _| t.id());
1091            Ok((
1092                worktree,
1093                ProjectPath {
1094                    worktree_id,
1095                    path: path.into(),
1096                },
1097            ))
1098        })
1099    }
1100
1101    /// Returns the modal that was toggled closed if it was open.
1102    pub fn toggle_modal<V, F>(
1103        &mut self,
1104        cx: &mut ViewContext<Self>,
1105        add_view: F,
1106    ) -> Option<ViewHandle<V>>
1107    where
1108        V: 'static + View,
1109        F: FnOnce(&mut Self, &mut ViewContext<Self>) -> ViewHandle<V>,
1110    {
1111        cx.notify();
1112        // Whatever modal was visible is getting clobbered. If its the same type as V, then return
1113        // it. Otherwise, create a new modal and set it as active.
1114        let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
1115        if let Some(already_open_modal) = already_open_modal {
1116            cx.focus_self();
1117            Some(already_open_modal)
1118        } else {
1119            let modal = add_view(self, cx);
1120            cx.focus(&modal);
1121            self.modal = Some(modal.into());
1122            None
1123        }
1124    }
1125
1126    pub fn modal(&self) -> Option<&AnyViewHandle> {
1127        self.modal.as_ref()
1128    }
1129
1130    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
1131        if self.modal.take().is_some() {
1132            cx.focus(&self.active_pane);
1133            cx.notify();
1134        }
1135    }
1136
1137    pub fn show_notification<V: Notification>(
1138        &mut self,
1139        id: usize,
1140        cx: &mut ViewContext<Self>,
1141        build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
1142    ) {
1143        let type_id = TypeId::of::<V>();
1144        if self
1145            .notifications
1146            .iter()
1147            .all(|(existing_type_id, existing_id, _)| {
1148                (*existing_type_id, *existing_id) != (type_id, id)
1149            })
1150        {
1151            let notification = build_notification(cx);
1152            cx.subscribe(&notification, move |this, handle, event, cx| {
1153                if handle.read(cx).should_dismiss_notification_on_event(event) {
1154                    this.dismiss_notification(type_id, id, cx);
1155                }
1156            })
1157            .detach();
1158            self.notifications
1159                .push((type_id, id, Box::new(notification)));
1160            cx.notify();
1161        }
1162    }
1163
1164    fn dismiss_notification(&mut self, type_id: TypeId, id: usize, cx: &mut ViewContext<Self>) {
1165        self.notifications
1166            .retain(|(existing_type_id, existing_id, _)| {
1167                if (*existing_type_id, *existing_id) == (type_id, id) {
1168                    cx.notify();
1169                    false
1170                } else {
1171                    true
1172                }
1173            });
1174    }
1175
1176    pub fn items<'a>(
1177        &'a self,
1178        cx: &'a AppContext,
1179    ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1180        self.panes.iter().flat_map(|pane| pane.read(cx).items())
1181    }
1182
1183    pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
1184        self.items_of_type(cx).max_by_key(|item| item.id())
1185    }
1186
1187    pub fn items_of_type<'a, T: Item>(
1188        &'a self,
1189        cx: &'a AppContext,
1190    ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
1191        self.panes
1192            .iter()
1193            .flat_map(|pane| pane.read(cx).items_of_type())
1194    }
1195
1196    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1197        self.active_pane().read(cx).active_item()
1198    }
1199
1200    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1201        self.active_item(cx).and_then(|item| item.project_path(cx))
1202    }
1203
1204    pub fn save_active_item(
1205        &mut self,
1206        force_name_change: bool,
1207        cx: &mut ViewContext<Self>,
1208    ) -> Task<Result<()>> {
1209        let project = self.project.clone();
1210        if let Some(item) = self.active_item(cx) {
1211            if !force_name_change && item.can_save(cx) {
1212                if item.has_conflict(cx.as_ref()) {
1213                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1214
1215                    let mut answer = cx.prompt(
1216                        PromptLevel::Warning,
1217                        CONFLICT_MESSAGE,
1218                        &["Overwrite", "Cancel"],
1219                    );
1220                    cx.spawn(|_, mut cx| async move {
1221                        let answer = answer.recv().await;
1222                        if answer == Some(0) {
1223                            cx.update(|cx| item.save(project, cx)).await?;
1224                        }
1225                        Ok(())
1226                    })
1227                } else {
1228                    item.save(project, cx)
1229                }
1230            } else if item.is_singleton(cx) {
1231                let worktree = self.worktrees(cx).next();
1232                let start_abs_path = worktree
1233                    .and_then(|w| w.read(cx).as_local())
1234                    .map_or(Path::new(""), |w| w.abs_path())
1235                    .to_path_buf();
1236                let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1237                cx.spawn(|_, mut cx| async move {
1238                    if let Some(abs_path) = abs_path.recv().await.flatten() {
1239                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1240                    }
1241                    Ok(())
1242                })
1243            } else {
1244                Task::ready(Ok(()))
1245            }
1246        } else {
1247            Task::ready(Ok(()))
1248        }
1249    }
1250
1251    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1252        let sidebar = match action.side {
1253            Side::Left => &mut self.left_sidebar,
1254            Side::Right => &mut self.right_sidebar,
1255        };
1256        let active_item = sidebar.update(cx, |sidebar, cx| {
1257            sidebar.toggle_item(action.item_index, cx);
1258            sidebar.active_item().map(|item| item.to_any())
1259        });
1260        if let Some(active_item) = active_item {
1261            cx.focus(active_item);
1262        } else {
1263            cx.focus_self();
1264        }
1265        cx.notify();
1266    }
1267
1268    pub fn toggle_sidebar_item_focus(
1269        &mut self,
1270        action: &ToggleSidebarItemFocus,
1271        cx: &mut ViewContext<Self>,
1272    ) {
1273        let sidebar = match action.side {
1274            Side::Left => &mut self.left_sidebar,
1275            Side::Right => &mut self.right_sidebar,
1276        };
1277        let active_item = sidebar.update(cx, |sidebar, cx| {
1278            sidebar.activate_item(action.item_index, cx);
1279            sidebar.active_item().cloned()
1280        });
1281        if let Some(active_item) = active_item {
1282            if active_item.is_focused(cx) {
1283                cx.focus_self();
1284            } else {
1285                cx.focus(active_item.to_any());
1286            }
1287        }
1288        cx.notify();
1289    }
1290
1291    pub fn focus_center(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
1292        cx.focus_self();
1293        cx.notify();
1294    }
1295
1296    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1297        let pane = cx.add_view(|cx| Pane::new(cx));
1298        let pane_id = pane.id();
1299        cx.subscribe(&pane, move |this, _, event, cx| {
1300            this.handle_pane_event(pane_id, event, cx)
1301        })
1302        .detach();
1303        self.panes.push(pane.clone());
1304        self.activate_pane(pane.clone(), cx);
1305        cx.emit(Event::PaneAdded(pane.clone()));
1306        pane
1307    }
1308
1309    pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1310        let pane = self.active_pane().clone();
1311        Pane::add_item(self, pane, item, true, true, cx);
1312    }
1313
1314    pub fn open_path(
1315        &mut self,
1316        path: impl Into<ProjectPath>,
1317        focus_item: bool,
1318        cx: &mut ViewContext<Self>,
1319    ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1320        let pane = self.active_pane().downgrade();
1321        let task = self.load_path(path.into(), cx);
1322        cx.spawn(|this, mut cx| async move {
1323            let (project_entry_id, build_item) = task.await?;
1324            let pane = pane
1325                .upgrade(&cx)
1326                .ok_or_else(|| anyhow!("pane was closed"))?;
1327            this.update(&mut cx, |this, cx| {
1328                Ok(Pane::open_item(
1329                    this,
1330                    pane,
1331                    project_entry_id,
1332                    focus_item,
1333                    cx,
1334                    build_item,
1335                ))
1336            })
1337        })
1338    }
1339
1340    pub(crate) fn load_path(
1341        &mut self,
1342        path: ProjectPath,
1343        cx: &mut ViewContext<Self>,
1344    ) -> Task<
1345        Result<(
1346            ProjectEntryId,
1347            impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1348        )>,
1349    > {
1350        let project = self.project().clone();
1351        let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1352        let window_id = cx.window_id();
1353        cx.as_mut().spawn(|mut cx| async move {
1354            let (project_entry_id, project_item) = project_item.await?;
1355            let build_item = cx.update(|cx| {
1356                cx.default_global::<ProjectItemBuilders>()
1357                    .get(&project_item.model_type())
1358                    .ok_or_else(|| anyhow!("no item builder for project item"))
1359                    .cloned()
1360            })?;
1361            let build_item =
1362                move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1363            Ok((project_entry_id, build_item))
1364        })
1365    }
1366
1367    pub fn open_project_item<T>(
1368        &mut self,
1369        project_item: ModelHandle<T::Item>,
1370        cx: &mut ViewContext<Self>,
1371    ) -> ViewHandle<T>
1372    where
1373        T: ProjectItem,
1374    {
1375        use project::Item as _;
1376
1377        let entry_id = project_item.read(cx).entry_id(cx);
1378        if let Some(item) = entry_id
1379            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1380            .and_then(|item| item.downcast())
1381        {
1382            self.activate_item(&item, cx);
1383            return item;
1384        }
1385
1386        let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1387        self.add_item(Box::new(item.clone()), cx);
1388        item
1389    }
1390
1391    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1392        let result = self.panes.iter().find_map(|pane| {
1393            if let Some(ix) = pane.read(cx).index_for_item(item) {
1394                Some((pane.clone(), ix))
1395            } else {
1396                None
1397            }
1398        });
1399        if let Some((pane, ix)) = result {
1400            self.activate_pane(pane.clone(), cx);
1401            pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, cx));
1402            true
1403        } else {
1404            false
1405        }
1406    }
1407
1408    pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1409        let next_pane = {
1410            let panes = self.center.panes();
1411            let ix = panes
1412                .iter()
1413                .position(|pane| **pane == self.active_pane)
1414                .unwrap();
1415            let next_ix = (ix + 1) % panes.len();
1416            panes[next_ix].clone()
1417        };
1418        self.activate_pane(next_pane, cx);
1419    }
1420
1421    pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1422        let prev_pane = {
1423            let panes = self.center.panes();
1424            let ix = panes
1425                .iter()
1426                .position(|pane| **pane == self.active_pane)
1427                .unwrap();
1428            let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1429            panes[prev_ix].clone()
1430        };
1431        self.activate_pane(prev_pane, cx);
1432    }
1433
1434    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1435        if self.active_pane != pane {
1436            self.active_pane = pane.clone();
1437            self.status_bar.update(cx, |status_bar, cx| {
1438                status_bar.set_active_pane(&self.active_pane, cx);
1439            });
1440            self.active_item_path_changed(cx);
1441            cx.focus(&self.active_pane);
1442            cx.notify();
1443        }
1444
1445        self.update_followers(
1446            proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1447                id: self.active_item(cx).map(|item| item.id() as u64),
1448                leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1449            }),
1450            cx,
1451        );
1452    }
1453
1454    fn handle_pane_event(
1455        &mut self,
1456        pane_id: usize,
1457        event: &pane::Event,
1458        cx: &mut ViewContext<Self>,
1459    ) {
1460        if let Some(pane) = self.pane(pane_id) {
1461            match event {
1462                pane::Event::Split(direction) => {
1463                    self.split_pane(pane, *direction, cx);
1464                }
1465                pane::Event::Remove => {
1466                    self.remove_pane(pane, cx);
1467                }
1468                pane::Event::Activate => {
1469                    self.activate_pane(pane, cx);
1470                }
1471                pane::Event::ActivateItem { local } => {
1472                    if *local {
1473                        self.unfollow(&pane, cx);
1474                    }
1475                    if pane == self.active_pane {
1476                        self.active_item_path_changed(cx);
1477                    }
1478                }
1479                pane::Event::ChangeItemTitle => {
1480                    if pane == self.active_pane {
1481                        self.active_item_path_changed(cx);
1482                    }
1483                    self.update_window_edited(cx);
1484                }
1485            }
1486        } else {
1487            error!("pane {} not found", pane_id);
1488        }
1489    }
1490
1491    pub fn split_pane(
1492        &mut self,
1493        pane: ViewHandle<Pane>,
1494        direction: SplitDirection,
1495        cx: &mut ViewContext<Self>,
1496    ) -> ViewHandle<Pane> {
1497        let new_pane = self.add_pane(cx);
1498        self.activate_pane(new_pane.clone(), cx);
1499        if let Some(item) = pane.read(cx).active_item() {
1500            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1501                Pane::add_item(self, new_pane.clone(), clone, true, true, cx);
1502            }
1503        }
1504        self.center.split(&pane, &new_pane, direction).unwrap();
1505        cx.notify();
1506        new_pane
1507    }
1508
1509    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1510        if self.center.remove(&pane).unwrap() {
1511            self.panes.retain(|p| p != &pane);
1512            self.activate_pane(self.panes.last().unwrap().clone(), cx);
1513            self.unfollow(&pane, cx);
1514            self.last_leaders_by_pane.remove(&pane.downgrade());
1515            cx.notify();
1516        } else {
1517            self.active_item_path_changed(cx);
1518        }
1519    }
1520
1521    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1522        &self.panes
1523    }
1524
1525    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1526        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1527    }
1528
1529    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1530        &self.active_pane
1531    }
1532
1533    fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1534        if let Some(remote_id) = remote_id {
1535            self.remote_entity_subscription =
1536                Some(self.client.add_view_for_remote_entity(remote_id, cx));
1537        } else {
1538            self.remote_entity_subscription.take();
1539        }
1540    }
1541
1542    fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1543        self.leader_state.followers.remove(&peer_id);
1544        if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1545            for state in states_by_pane.into_values() {
1546                for item in state.items_by_leader_view_id.into_values() {
1547                    if let FollowerItem::Loaded(item) = item {
1548                        item.set_leader_replica_id(None, cx);
1549                    }
1550                }
1551            }
1552        }
1553        cx.notify();
1554    }
1555
1556    pub fn toggle_follow(
1557        &mut self,
1558        ToggleFollow(leader_id): &ToggleFollow,
1559        cx: &mut ViewContext<Self>,
1560    ) -> Option<Task<Result<()>>> {
1561        let leader_id = *leader_id;
1562        let pane = self.active_pane().clone();
1563
1564        if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1565            if leader_id == prev_leader_id {
1566                return None;
1567            }
1568        }
1569
1570        self.last_leaders_by_pane
1571            .insert(pane.downgrade(), leader_id);
1572        self.follower_states_by_leader
1573            .entry(leader_id)
1574            .or_default()
1575            .insert(pane.clone(), Default::default());
1576        cx.notify();
1577
1578        let project_id = self.project.read(cx).remote_id()?;
1579        let request = self.client.request(proto::Follow {
1580            project_id,
1581            leader_id: leader_id.0,
1582        });
1583        Some(cx.spawn_weak(|this, mut cx| async move {
1584            let response = request.await?;
1585            if let Some(this) = this.upgrade(&cx) {
1586                this.update(&mut cx, |this, _| {
1587                    let state = this
1588                        .follower_states_by_leader
1589                        .get_mut(&leader_id)
1590                        .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1591                        .ok_or_else(|| anyhow!("following interrupted"))?;
1592                    state.active_view_id = response.active_view_id;
1593                    Ok::<_, anyhow::Error>(())
1594                })?;
1595                Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1596                    .await?;
1597            }
1598            Ok(())
1599        }))
1600    }
1601
1602    pub fn follow_next_collaborator(
1603        &mut self,
1604        _: &FollowNextCollaborator,
1605        cx: &mut ViewContext<Self>,
1606    ) -> Option<Task<Result<()>>> {
1607        let collaborators = self.project.read(cx).collaborators();
1608        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1609            let mut collaborators = collaborators.keys().copied();
1610            while let Some(peer_id) = collaborators.next() {
1611                if peer_id == leader_id {
1612                    break;
1613                }
1614            }
1615            collaborators.next()
1616        } else if let Some(last_leader_id) =
1617            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1618        {
1619            if collaborators.contains_key(last_leader_id) {
1620                Some(*last_leader_id)
1621            } else {
1622                None
1623            }
1624        } else {
1625            None
1626        };
1627
1628        next_leader_id
1629            .or_else(|| collaborators.keys().copied().next())
1630            .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1631    }
1632
1633    pub fn unfollow(
1634        &mut self,
1635        pane: &ViewHandle<Pane>,
1636        cx: &mut ViewContext<Self>,
1637    ) -> Option<PeerId> {
1638        for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1639            let leader_id = *leader_id;
1640            if let Some(state) = states_by_pane.remove(&pane) {
1641                for (_, item) in state.items_by_leader_view_id {
1642                    if let FollowerItem::Loaded(item) = item {
1643                        item.set_leader_replica_id(None, cx);
1644                    }
1645                }
1646
1647                if states_by_pane.is_empty() {
1648                    self.follower_states_by_leader.remove(&leader_id);
1649                    if let Some(project_id) = self.project.read(cx).remote_id() {
1650                        self.client
1651                            .send(proto::Unfollow {
1652                                project_id,
1653                                leader_id: leader_id.0,
1654                            })
1655                            .log_err();
1656                    }
1657                }
1658
1659                cx.notify();
1660                return Some(leader_id);
1661            }
1662        }
1663        None
1664    }
1665
1666    fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1667        let theme = &cx.global::<Settings>().theme;
1668        match &*self.client.status().borrow() {
1669            client::Status::ConnectionError
1670            | client::Status::ConnectionLost
1671            | client::Status::Reauthenticating
1672            | client::Status::Reconnecting { .. }
1673            | client::Status::ReconnectionError { .. } => Some(
1674                Container::new(
1675                    Align::new(
1676                        ConstrainedBox::new(
1677                            Svg::new("icons/offline-14.svg")
1678                                .with_color(theme.workspace.titlebar.offline_icon.color)
1679                                .boxed(),
1680                        )
1681                        .with_width(theme.workspace.titlebar.offline_icon.width)
1682                        .boxed(),
1683                    )
1684                    .boxed(),
1685                )
1686                .with_style(theme.workspace.titlebar.offline_icon.container)
1687                .boxed(),
1688            ),
1689            client::Status::UpgradeRequired => Some(
1690                Label::new(
1691                    "Please update Zed to collaborate".to_string(),
1692                    theme.workspace.titlebar.outdated_warning.text.clone(),
1693                )
1694                .contained()
1695                .with_style(theme.workspace.titlebar.outdated_warning.container)
1696                .aligned()
1697                .boxed(),
1698            ),
1699            _ => None,
1700        }
1701    }
1702
1703    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1704        let project = &self.project.read(cx);
1705        let replica_id = project.replica_id();
1706        let mut worktree_root_names = String::new();
1707        for (i, name) in project.worktree_root_names(cx).enumerate() {
1708            if i > 0 {
1709                worktree_root_names.push_str(", ");
1710            }
1711            worktree_root_names.push_str(name);
1712        }
1713
1714        ConstrainedBox::new(
1715            Container::new(
1716                Stack::new()
1717                    .with_child(
1718                        Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
1719                            .aligned()
1720                            .left()
1721                            .boxed(),
1722                    )
1723                    .with_child(
1724                        Align::new(
1725                            Flex::row()
1726                                .with_children(self.render_collaborators(theme, cx))
1727                                .with_children(self.render_current_user(
1728                                    self.user_store.read(cx).current_user().as_ref(),
1729                                    replica_id,
1730                                    theme,
1731                                    cx,
1732                                ))
1733                                .with_children(self.render_connection_status(cx))
1734                                .boxed(),
1735                        )
1736                        .right()
1737                        .boxed(),
1738                    )
1739                    .boxed(),
1740            )
1741            .with_style(theme.workspace.titlebar.container)
1742            .boxed(),
1743        )
1744        .with_height(theme.workspace.titlebar.height)
1745        .named("titlebar")
1746    }
1747
1748    fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
1749        let active_entry = self.active_project_path(cx);
1750        self.project
1751            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1752        self.update_window_title(cx);
1753    }
1754
1755    fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
1756        let mut title = String::new();
1757        let project = self.project().read(cx);
1758        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
1759            let filename = path
1760                .path
1761                .file_name()
1762                .map(|s| s.to_string_lossy())
1763                .or_else(|| {
1764                    Some(Cow::Borrowed(
1765                        project
1766                            .worktree_for_id(path.worktree_id, cx)?
1767                            .read(cx)
1768                            .root_name(),
1769                    ))
1770                });
1771            if let Some(filename) = filename {
1772                title.push_str(filename.as_ref());
1773                title.push_str("");
1774            }
1775        }
1776        for (i, name) in project.worktree_root_names(cx).enumerate() {
1777            if i > 0 {
1778                title.push_str(", ");
1779            }
1780            title.push_str(name);
1781        }
1782        if title.is_empty() {
1783            title = "empty project".to_string();
1784        }
1785        cx.set_window_title(&title);
1786    }
1787
1788    fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
1789        let is_edited = self
1790            .items(cx)
1791            .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
1792        if is_edited != self.window_edited {
1793            self.window_edited = is_edited;
1794            cx.set_window_edited(self.window_edited)
1795        }
1796    }
1797
1798    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1799        let mut collaborators = self
1800            .project
1801            .read(cx)
1802            .collaborators()
1803            .values()
1804            .cloned()
1805            .collect::<Vec<_>>();
1806        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1807        collaborators
1808            .into_iter()
1809            .filter_map(|collaborator| {
1810                Some(self.render_avatar(
1811                    collaborator.user.avatar.clone()?,
1812                    collaborator.replica_id,
1813                    Some((collaborator.peer_id, &collaborator.user.github_login)),
1814                    theme,
1815                    cx,
1816                ))
1817            })
1818            .collect()
1819    }
1820
1821    fn render_current_user(
1822        &self,
1823        user: Option<&Arc<User>>,
1824        replica_id: ReplicaId,
1825        theme: &Theme,
1826        cx: &mut RenderContext<Self>,
1827    ) -> Option<ElementBox> {
1828        let status = *self.client.status().borrow();
1829        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1830            Some(self.render_avatar(avatar, replica_id, None, theme, cx))
1831        } else if matches!(status, client::Status::UpgradeRequired) {
1832            None
1833        } else {
1834            Some(
1835                MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1836                    let style = theme
1837                        .workspace
1838                        .titlebar
1839                        .sign_in_prompt
1840                        .style_for(state, false);
1841                    Label::new("Sign in".to_string(), style.text.clone())
1842                        .contained()
1843                        .with_style(style.container)
1844                        .boxed()
1845                })
1846                .on_click(|_, _, cx| cx.dispatch_action(Authenticate))
1847                .with_cursor_style(CursorStyle::PointingHand)
1848                .aligned()
1849                .boxed(),
1850            )
1851        }
1852    }
1853
1854    fn render_avatar(
1855        &self,
1856        avatar: Arc<ImageData>,
1857        replica_id: ReplicaId,
1858        peer: Option<(PeerId, &str)>,
1859        theme: &Theme,
1860        cx: &mut RenderContext<Self>,
1861    ) -> ElementBox {
1862        let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1863        let is_followed = peer.map_or(false, |(peer_id, _)| {
1864            self.follower_states_by_leader.contains_key(&peer_id)
1865        });
1866        let mut avatar_style = theme.workspace.titlebar.avatar;
1867        if is_followed {
1868            avatar_style.border = Border::all(1.0, replica_color);
1869        }
1870        let content = Stack::new()
1871            .with_child(
1872                Image::new(avatar)
1873                    .with_style(avatar_style)
1874                    .constrained()
1875                    .with_width(theme.workspace.titlebar.avatar_width)
1876                    .aligned()
1877                    .boxed(),
1878            )
1879            .with_child(
1880                AvatarRibbon::new(replica_color)
1881                    .constrained()
1882                    .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1883                    .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1884                    .aligned()
1885                    .bottom()
1886                    .boxed(),
1887            )
1888            .constrained()
1889            .with_width(theme.workspace.titlebar.avatar_width)
1890            .contained()
1891            .with_margin_left(theme.workspace.titlebar.avatar_margin)
1892            .boxed();
1893
1894        if let Some((peer_id, peer_github_login)) = peer {
1895            MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1896                .with_cursor_style(CursorStyle::PointingHand)
1897                .on_click(move |_, _, cx| cx.dispatch_action(ToggleFollow(peer_id)))
1898                .with_tooltip::<ToggleFollow, _>(
1899                    peer_id.0 as usize,
1900                    if is_followed {
1901                        format!("Unfollow {}", peer_github_login)
1902                    } else {
1903                        format!("Follow {}", peer_github_login)
1904                    },
1905                    Some(Box::new(FollowNextCollaborator)),
1906                    theme.tooltip.clone(),
1907                    cx,
1908                )
1909                .boxed()
1910        } else {
1911            content
1912        }
1913    }
1914
1915    fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1916        if self.project.read(cx).is_read_only() {
1917            let theme = &cx.global::<Settings>().theme;
1918            Some(
1919                EventHandler::new(
1920                    Label::new(
1921                        "Your connection to the remote project has been lost.".to_string(),
1922                        theme.workspace.disconnected_overlay.text.clone(),
1923                    )
1924                    .aligned()
1925                    .contained()
1926                    .with_style(theme.workspace.disconnected_overlay.container)
1927                    .boxed(),
1928                )
1929                .capture_all::<Self>(0)
1930                .boxed(),
1931            )
1932        } else {
1933            None
1934        }
1935    }
1936
1937    fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
1938        if self.notifications.is_empty() {
1939            None
1940        } else {
1941            Some(
1942                Flex::column()
1943                    .with_children(self.notifications.iter().map(|(_, _, notification)| {
1944                        ChildView::new(notification.as_ref())
1945                            .contained()
1946                            .with_style(theme.notification)
1947                            .boxed()
1948                    }))
1949                    .constrained()
1950                    .with_width(theme.notifications.width)
1951                    .contained()
1952                    .with_style(theme.notifications.container)
1953                    .aligned()
1954                    .bottom()
1955                    .right()
1956                    .boxed(),
1957            )
1958        }
1959    }
1960
1961    // RPC handlers
1962
1963    async fn handle_follow(
1964        this: ViewHandle<Self>,
1965        envelope: TypedEnvelope<proto::Follow>,
1966        _: Arc<Client>,
1967        mut cx: AsyncAppContext,
1968    ) -> Result<proto::FollowResponse> {
1969        this.update(&mut cx, |this, cx| {
1970            this.leader_state
1971                .followers
1972                .insert(envelope.original_sender_id()?);
1973
1974            let active_view_id = this
1975                .active_item(cx)
1976                .and_then(|i| i.to_followable_item_handle(cx))
1977                .map(|i| i.id() as u64);
1978            Ok(proto::FollowResponse {
1979                active_view_id,
1980                views: this
1981                    .panes()
1982                    .iter()
1983                    .flat_map(|pane| {
1984                        let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1985                        pane.read(cx).items().filter_map({
1986                            let cx = &cx;
1987                            move |item| {
1988                                let id = item.id() as u64;
1989                                let item = item.to_followable_item_handle(cx)?;
1990                                let variant = item.to_state_proto(cx)?;
1991                                Some(proto::View {
1992                                    id,
1993                                    leader_id,
1994                                    variant: Some(variant),
1995                                })
1996                            }
1997                        })
1998                    })
1999                    .collect(),
2000            })
2001        })
2002    }
2003
2004    async fn handle_unfollow(
2005        this: ViewHandle<Self>,
2006        envelope: TypedEnvelope<proto::Unfollow>,
2007        _: Arc<Client>,
2008        mut cx: AsyncAppContext,
2009    ) -> Result<()> {
2010        this.update(&mut cx, |this, _| {
2011            this.leader_state
2012                .followers
2013                .remove(&envelope.original_sender_id()?);
2014            Ok(())
2015        })
2016    }
2017
2018    async fn handle_update_followers(
2019        this: ViewHandle<Self>,
2020        envelope: TypedEnvelope<proto::UpdateFollowers>,
2021        _: Arc<Client>,
2022        mut cx: AsyncAppContext,
2023    ) -> Result<()> {
2024        let leader_id = envelope.original_sender_id()?;
2025        match envelope
2026            .payload
2027            .variant
2028            .ok_or_else(|| anyhow!("invalid update"))?
2029        {
2030            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2031                this.update(&mut cx, |this, cx| {
2032                    this.update_leader_state(leader_id, cx, |state, _| {
2033                        state.active_view_id = update_active_view.id;
2034                    });
2035                    Ok::<_, anyhow::Error>(())
2036                })
2037            }
2038            proto::update_followers::Variant::UpdateView(update_view) => {
2039                this.update(&mut cx, |this, cx| {
2040                    let variant = update_view
2041                        .variant
2042                        .ok_or_else(|| anyhow!("missing update view variant"))?;
2043                    this.update_leader_state(leader_id, cx, |state, cx| {
2044                        let variant = variant.clone();
2045                        match state
2046                            .items_by_leader_view_id
2047                            .entry(update_view.id)
2048                            .or_insert(FollowerItem::Loading(Vec::new()))
2049                        {
2050                            FollowerItem::Loaded(item) => {
2051                                item.apply_update_proto(variant, cx).log_err();
2052                            }
2053                            FollowerItem::Loading(updates) => updates.push(variant),
2054                        }
2055                    });
2056                    Ok(())
2057                })
2058            }
2059            proto::update_followers::Variant::CreateView(view) => {
2060                let panes = this.read_with(&cx, |this, _| {
2061                    this.follower_states_by_leader
2062                        .get(&leader_id)
2063                        .into_iter()
2064                        .flat_map(|states_by_pane| states_by_pane.keys())
2065                        .cloned()
2066                        .collect()
2067                });
2068                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
2069                    .await?;
2070                Ok(())
2071            }
2072        }
2073        .log_err();
2074
2075        Ok(())
2076    }
2077
2078    async fn add_views_from_leader(
2079        this: ViewHandle<Self>,
2080        leader_id: PeerId,
2081        panes: Vec<ViewHandle<Pane>>,
2082        views: Vec<proto::View>,
2083        cx: &mut AsyncAppContext,
2084    ) -> Result<()> {
2085        let project = this.read_with(cx, |this, _| this.project.clone());
2086        let replica_id = project
2087            .read_with(cx, |project, _| {
2088                project
2089                    .collaborators()
2090                    .get(&leader_id)
2091                    .map(|c| c.replica_id)
2092            })
2093            .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
2094
2095        let item_builders = cx.update(|cx| {
2096            cx.default_global::<FollowableItemBuilders>()
2097                .values()
2098                .map(|b| b.0)
2099                .collect::<Vec<_>>()
2100                .clone()
2101        });
2102
2103        let mut item_tasks_by_pane = HashMap::default();
2104        for pane in panes {
2105            let mut item_tasks = Vec::new();
2106            let mut leader_view_ids = Vec::new();
2107            for view in &views {
2108                let mut variant = view.variant.clone();
2109                if variant.is_none() {
2110                    Err(anyhow!("missing variant"))?;
2111                }
2112                for build_item in &item_builders {
2113                    let task =
2114                        cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
2115                    if let Some(task) = task {
2116                        item_tasks.push(task);
2117                        leader_view_ids.push(view.id);
2118                        break;
2119                    } else {
2120                        assert!(variant.is_some());
2121                    }
2122                }
2123            }
2124
2125            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2126        }
2127
2128        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2129            let items = futures::future::try_join_all(item_tasks).await?;
2130            this.update(cx, |this, cx| {
2131                let state = this
2132                    .follower_states_by_leader
2133                    .get_mut(&leader_id)?
2134                    .get_mut(&pane)?;
2135
2136                for (id, item) in leader_view_ids.into_iter().zip(items) {
2137                    item.set_leader_replica_id(Some(replica_id), cx);
2138                    match state.items_by_leader_view_id.entry(id) {
2139                        hash_map::Entry::Occupied(e) => {
2140                            let e = e.into_mut();
2141                            if let FollowerItem::Loading(updates) = e {
2142                                for update in updates.drain(..) {
2143                                    item.apply_update_proto(update, cx)
2144                                        .context("failed to apply view update")
2145                                        .log_err();
2146                                }
2147                            }
2148                            *e = FollowerItem::Loaded(item);
2149                        }
2150                        hash_map::Entry::Vacant(e) => {
2151                            e.insert(FollowerItem::Loaded(item));
2152                        }
2153                    }
2154                }
2155
2156                Some(())
2157            });
2158        }
2159        this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
2160
2161        Ok(())
2162    }
2163
2164    fn update_followers(
2165        &self,
2166        update: proto::update_followers::Variant,
2167        cx: &AppContext,
2168    ) -> Option<()> {
2169        let project_id = self.project.read(cx).remote_id()?;
2170        if !self.leader_state.followers.is_empty() {
2171            self.client
2172                .send(proto::UpdateFollowers {
2173                    project_id,
2174                    follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
2175                    variant: Some(update),
2176                })
2177                .log_err();
2178        }
2179        None
2180    }
2181
2182    pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
2183        self.follower_states_by_leader
2184            .iter()
2185            .find_map(|(leader_id, state)| {
2186                if state.contains_key(pane) {
2187                    Some(*leader_id)
2188                } else {
2189                    None
2190                }
2191            })
2192    }
2193
2194    fn update_leader_state(
2195        &mut self,
2196        leader_id: PeerId,
2197        cx: &mut ViewContext<Self>,
2198        mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
2199    ) {
2200        for (_, state) in self
2201            .follower_states_by_leader
2202            .get_mut(&leader_id)
2203            .into_iter()
2204            .flatten()
2205        {
2206            update_fn(state, cx);
2207        }
2208        self.leader_updated(leader_id, cx);
2209    }
2210
2211    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2212        let mut items_to_add = Vec::new();
2213        for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2214            if let Some(active_item) = state
2215                .active_view_id
2216                .and_then(|id| state.items_by_leader_view_id.get(&id))
2217            {
2218                if let FollowerItem::Loaded(item) = active_item {
2219                    items_to_add.push((pane.clone(), item.boxed_clone()));
2220                }
2221            }
2222        }
2223
2224        for (pane, item) in items_to_add {
2225            Pane::add_item(self, pane.clone(), item.boxed_clone(), false, false, cx);
2226            if pane == self.active_pane {
2227                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2228            }
2229            cx.notify();
2230        }
2231        None
2232    }
2233}
2234
2235impl Entity for Workspace {
2236    type Event = Event;
2237}
2238
2239impl View for Workspace {
2240    fn ui_name() -> &'static str {
2241        "Workspace"
2242    }
2243
2244    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2245        let theme = cx.global::<Settings>().theme.clone();
2246        Stack::new()
2247            .with_child(
2248                Flex::column()
2249                    .with_child(self.render_titlebar(&theme, cx))
2250                    .with_child(
2251                        Stack::new()
2252                            .with_child({
2253                                Flex::row()
2254                                    .with_children(
2255                                        if self.left_sidebar.read(cx).active_item().is_some() {
2256                                            Some(
2257                                                ChildView::new(&self.left_sidebar)
2258                                                    .flex(0.8, false)
2259                                                    .boxed(),
2260                                            )
2261                                        } else {
2262                                            None
2263                                        },
2264                                    )
2265                                    .with_child(
2266                                        FlexItem::new(self.center.render(
2267                                            &theme,
2268                                            &self.follower_states_by_leader,
2269                                            self.project.read(cx).collaborators(),
2270                                        ))
2271                                        .flex(1., true)
2272                                        .boxed(),
2273                                    )
2274                                    .with_children(
2275                                        if self.right_sidebar.read(cx).active_item().is_some() {
2276                                            Some(
2277                                                ChildView::new(&self.right_sidebar)
2278                                                    .flex(0.8, false)
2279                                                    .boxed(),
2280                                            )
2281                                        } else {
2282                                            None
2283                                        },
2284                                    )
2285                                    .boxed()
2286                            })
2287                            .with_children(self.modal.as_ref().map(|m| {
2288                                ChildView::new(m)
2289                                    .contained()
2290                                    .with_style(theme.workspace.modal)
2291                                    .aligned()
2292                                    .top()
2293                                    .boxed()
2294                            }))
2295                            .with_children(self.render_notifications(&theme.workspace))
2296                            .flex(1.0, true)
2297                            .boxed(),
2298                    )
2299                    .with_child(ChildView::new(&self.status_bar).boxed())
2300                    .contained()
2301                    .with_background_color(theme.workspace.background)
2302                    .boxed(),
2303            )
2304            .with_children(self.render_disconnected_overlay(cx))
2305            .named("workspace")
2306    }
2307
2308    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2309        cx.focus(&self.active_pane);
2310    }
2311}
2312
2313pub trait WorkspaceHandle {
2314    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2315}
2316
2317impl WorkspaceHandle for ViewHandle<Workspace> {
2318    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2319        self.read(cx)
2320            .worktrees(cx)
2321            .flat_map(|worktree| {
2322                let worktree_id = worktree.read(cx).id();
2323                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2324                    worktree_id,
2325                    path: f.path.clone(),
2326                })
2327            })
2328            .collect::<Vec<_>>()
2329    }
2330}
2331
2332pub struct AvatarRibbon {
2333    color: Color,
2334}
2335
2336impl AvatarRibbon {
2337    pub fn new(color: Color) -> AvatarRibbon {
2338        AvatarRibbon { color }
2339    }
2340}
2341
2342impl Element for AvatarRibbon {
2343    type LayoutState = ();
2344
2345    type PaintState = ();
2346
2347    fn layout(
2348        &mut self,
2349        constraint: gpui::SizeConstraint,
2350        _: &mut gpui::LayoutContext,
2351    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2352        (constraint.max, ())
2353    }
2354
2355    fn paint(
2356        &mut self,
2357        bounds: gpui::geometry::rect::RectF,
2358        _: gpui::geometry::rect::RectF,
2359        _: &mut Self::LayoutState,
2360        cx: &mut gpui::PaintContext,
2361    ) -> Self::PaintState {
2362        let mut path = PathBuilder::new();
2363        path.reset(bounds.lower_left());
2364        path.curve_to(
2365            bounds.origin() + vec2f(bounds.height(), 0.),
2366            bounds.origin(),
2367        );
2368        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2369        path.curve_to(bounds.lower_right(), bounds.upper_right());
2370        path.line_to(bounds.lower_left());
2371        cx.scene.push_path(path.build(self.color, None));
2372    }
2373
2374    fn dispatch_event(
2375        &mut self,
2376        _: &gpui::Event,
2377        _: RectF,
2378        _: RectF,
2379        _: &mut Self::LayoutState,
2380        _: &mut Self::PaintState,
2381        _: &mut gpui::EventContext,
2382    ) -> bool {
2383        false
2384    }
2385
2386    fn debug(
2387        &self,
2388        bounds: gpui::geometry::rect::RectF,
2389        _: &Self::LayoutState,
2390        _: &Self::PaintState,
2391        _: &gpui::DebugContext,
2392    ) -> gpui::json::Value {
2393        json::json!({
2394            "type": "AvatarRibbon",
2395            "bounds": bounds.to_json(),
2396            "color": self.color.to_json(),
2397        })
2398    }
2399}
2400
2401impl std::fmt::Debug for OpenPaths {
2402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2403        f.debug_struct("OpenPaths")
2404            .field("paths", &self.paths)
2405            .finish()
2406    }
2407}
2408
2409fn open(_: &Open, cx: &mut MutableAppContext) {
2410    let mut paths = cx.prompt_for_paths(PathPromptOptions {
2411        files: true,
2412        directories: true,
2413        multiple: true,
2414    });
2415    cx.spawn(|mut cx| async move {
2416        if let Some(paths) = paths.recv().await.flatten() {
2417            cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2418        }
2419    })
2420    .detach();
2421}
2422
2423pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2424
2425pub fn activate_workspace_for_project(
2426    cx: &mut MutableAppContext,
2427    predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2428) -> Option<ViewHandle<Workspace>> {
2429    for window_id in cx.window_ids().collect::<Vec<_>>() {
2430        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2431            let project = workspace_handle.read(cx).project.clone();
2432            if project.update(cx, &predicate) {
2433                cx.activate_window(window_id);
2434                return Some(workspace_handle);
2435            }
2436        }
2437    }
2438    None
2439}
2440
2441pub fn open_paths(
2442    abs_paths: &[PathBuf],
2443    app_state: &Arc<AppState>,
2444    cx: &mut MutableAppContext,
2445) -> Task<(
2446    ViewHandle<Workspace>,
2447    Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2448)> {
2449    log::info!("open paths {:?}", abs_paths);
2450
2451    // Open paths in existing workspace if possible
2452    let existing =
2453        activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2454
2455    let app_state = app_state.clone();
2456    let abs_paths = abs_paths.to_vec();
2457    cx.spawn(|mut cx| async move {
2458        let mut new_project = None;
2459        let workspace = if let Some(existing) = existing {
2460            existing
2461        } else {
2462            let contains_directory =
2463                futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2464                    .await
2465                    .contains(&false);
2466
2467            cx.add_window((app_state.build_window_options)(), |cx| {
2468                let project = Project::local(
2469                    false,
2470                    app_state.client.clone(),
2471                    app_state.user_store.clone(),
2472                    app_state.project_store.clone(),
2473                    app_state.languages.clone(),
2474                    app_state.fs.clone(),
2475                    cx,
2476                );
2477                new_project = Some(project.clone());
2478                let mut workspace = Workspace::new(project, cx);
2479                (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2480                if contains_directory {
2481                    workspace.toggle_sidebar_item(
2482                        &ToggleSidebarItem {
2483                            side: Side::Left,
2484                            item_index: 0,
2485                        },
2486                        cx,
2487                    );
2488                }
2489                workspace
2490            })
2491            .1
2492        };
2493
2494        let items = workspace
2495            .update(&mut cx, |workspace, cx| {
2496                workspace.open_paths(abs_paths, true, cx)
2497            })
2498            .await;
2499
2500        if let Some(project) = new_project {
2501            project
2502                .update(&mut cx, |project, cx| project.restore_state(cx))
2503                .await
2504                .log_err();
2505        }
2506
2507        (workspace, items)
2508    })
2509}
2510
2511pub fn join_project(
2512    contact: Arc<Contact>,
2513    project_index: usize,
2514    app_state: &Arc<AppState>,
2515    cx: &mut MutableAppContext,
2516) {
2517    let project_id = contact.projects[project_index].id;
2518
2519    for window_id in cx.window_ids().collect::<Vec<_>>() {
2520        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2521            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2522                cx.activate_window(window_id);
2523                return;
2524            }
2525        }
2526    }
2527
2528    cx.add_window((app_state.build_window_options)(), |cx| {
2529        WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2530    });
2531}
2532
2533fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2534    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2535        let mut workspace = Workspace::new(
2536            Project::local(
2537                false,
2538                app_state.client.clone(),
2539                app_state.user_store.clone(),
2540                app_state.project_store.clone(),
2541                app_state.languages.clone(),
2542                app_state.fs.clone(),
2543                cx,
2544            ),
2545            cx,
2546        );
2547        (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2548        workspace
2549    });
2550    cx.dispatch_action(window_id, vec![workspace.id()], &NewFile);
2551}
2552
2553#[cfg(test)]
2554mod tests {
2555    use super::*;
2556    use gpui::{ModelHandle, TestAppContext, ViewContext};
2557    use project::{FakeFs, Project, ProjectEntryId};
2558    use serde_json::json;
2559
2560    #[gpui::test]
2561    async fn test_tracking_active_path(cx: &mut TestAppContext) {
2562        cx.foreground().forbid_parking();
2563        Settings::test_async(cx);
2564        let fs = FakeFs::new(cx.background());
2565        fs.insert_tree(
2566            "/root1",
2567            json!({
2568                "one.txt": "",
2569                "two.txt": "",
2570            }),
2571        )
2572        .await;
2573        fs.insert_tree(
2574            "/root2",
2575            json!({
2576                "three.txt": "",
2577            }),
2578        )
2579        .await;
2580
2581        let project = Project::test(fs, ["root1".as_ref()], cx).await;
2582        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2583        let worktree_id = project.read_with(cx, |project, cx| {
2584            project.worktrees(cx).next().unwrap().read(cx).id()
2585        });
2586
2587        let item1 = cx.add_view(window_id, |_| {
2588            let mut item = TestItem::new();
2589            item.project_path = Some((worktree_id, "one.txt").into());
2590            item
2591        });
2592        let item2 = cx.add_view(window_id, |_| {
2593            let mut item = TestItem::new();
2594            item.project_path = Some((worktree_id, "two.txt").into());
2595            item
2596        });
2597
2598        // Add an item to an empty pane
2599        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
2600        project.read_with(cx, |project, cx| {
2601            assert_eq!(
2602                project.active_entry(),
2603                project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2604            );
2605        });
2606        assert_eq!(
2607            cx.current_window_title(window_id).as_deref(),
2608            Some("one.txt — root1")
2609        );
2610
2611        // Add a second item to a non-empty pane
2612        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
2613        assert_eq!(
2614            cx.current_window_title(window_id).as_deref(),
2615            Some("two.txt — root1")
2616        );
2617        project.read_with(cx, |project, cx| {
2618            assert_eq!(
2619                project.active_entry(),
2620                project.entry_for_path(&(worktree_id, "two.txt").into(), cx)
2621            );
2622        });
2623
2624        // Close the active item
2625        workspace
2626            .update(cx, |workspace, cx| {
2627                Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
2628            })
2629            .await
2630            .unwrap();
2631        assert_eq!(
2632            cx.current_window_title(window_id).as_deref(),
2633            Some("one.txt — root1")
2634        );
2635        project.read_with(cx, |project, cx| {
2636            assert_eq!(
2637                project.active_entry(),
2638                project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2639            );
2640        });
2641
2642        // Add a project folder
2643        project
2644            .update(cx, |project, cx| {
2645                project.find_or_create_local_worktree("/root2", true, cx)
2646            })
2647            .await
2648            .unwrap();
2649        assert_eq!(
2650            cx.current_window_title(window_id).as_deref(),
2651            Some("one.txt — root1, root2")
2652        );
2653
2654        // Remove a project folder
2655        project.update(cx, |project, cx| {
2656            project.remove_worktree(worktree_id, cx);
2657        });
2658        assert_eq!(
2659            cx.current_window_title(window_id).as_deref(),
2660            Some("one.txt — root2")
2661        );
2662    }
2663
2664    #[gpui::test]
2665    async fn test_close_window(cx: &mut TestAppContext) {
2666        cx.foreground().forbid_parking();
2667        Settings::test_async(cx);
2668        let fs = FakeFs::new(cx.background());
2669        fs.insert_tree("/root", json!({ "one": "" })).await;
2670
2671        let project = Project::test(fs, ["root".as_ref()], cx).await;
2672        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2673
2674        // When there are no dirty items, there's nothing to do.
2675        let item1 = cx.add_view(window_id, |_| TestItem::new());
2676        workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
2677        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2678        assert_eq!(task.await.unwrap(), true);
2679
2680        // When there are dirty untitled items, prompt to save each one. If the user
2681        // cancels any prompt, then abort.
2682        let item2 = cx.add_view(window_id, |_| {
2683            let mut item = TestItem::new();
2684            item.is_dirty = true;
2685            item
2686        });
2687        let item3 = cx.add_view(window_id, |_| {
2688            let mut item = TestItem::new();
2689            item.is_dirty = true;
2690            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2691            item
2692        });
2693        workspace.update(cx, |w, cx| {
2694            w.add_item(Box::new(item2.clone()), cx);
2695            w.add_item(Box::new(item3.clone()), cx);
2696        });
2697        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2698        cx.foreground().run_until_parked();
2699        cx.simulate_prompt_answer(window_id, 2 /* cancel */);
2700        cx.foreground().run_until_parked();
2701        assert!(!cx.has_pending_prompt(window_id));
2702        assert_eq!(task.await.unwrap(), false);
2703    }
2704
2705    #[gpui::test]
2706    async fn test_close_pane_items(cx: &mut TestAppContext) {
2707        cx.foreground().forbid_parking();
2708        Settings::test_async(cx);
2709        let fs = FakeFs::new(cx.background());
2710
2711        let project = Project::test(fs, None, cx).await;
2712        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
2713
2714        let item1 = cx.add_view(window_id, |_| {
2715            let mut item = TestItem::new();
2716            item.is_dirty = true;
2717            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2718            item
2719        });
2720        let item2 = cx.add_view(window_id, |_| {
2721            let mut item = TestItem::new();
2722            item.is_dirty = true;
2723            item.has_conflict = true;
2724            item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
2725            item
2726        });
2727        let item3 = cx.add_view(window_id, |_| {
2728            let mut item = TestItem::new();
2729            item.is_dirty = true;
2730            item.has_conflict = true;
2731            item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
2732            item
2733        });
2734        let item4 = cx.add_view(window_id, |_| {
2735            let mut item = TestItem::new();
2736            item.is_dirty = true;
2737            item
2738        });
2739        let pane = workspace.update(cx, |workspace, cx| {
2740            workspace.add_item(Box::new(item1.clone()), cx);
2741            workspace.add_item(Box::new(item2.clone()), cx);
2742            workspace.add_item(Box::new(item3.clone()), cx);
2743            workspace.add_item(Box::new(item4.clone()), cx);
2744            workspace.active_pane().clone()
2745        });
2746
2747        let close_items = workspace.update(cx, |workspace, cx| {
2748            pane.update(cx, |pane, cx| {
2749                pane.activate_item(1, true, true, cx);
2750                assert_eq!(pane.active_item().unwrap().id(), item2.id());
2751            });
2752
2753            let item1_id = item1.id();
2754            let item3_id = item3.id();
2755            let item4_id = item4.id();
2756            Pane::close_items(workspace, pane.clone(), cx, move |id| {
2757                [item1_id, item3_id, item4_id].contains(&id)
2758            })
2759        });
2760
2761        cx.foreground().run_until_parked();
2762        pane.read_with(cx, |pane, _| {
2763            assert_eq!(pane.items().count(), 4);
2764            assert_eq!(pane.active_item().unwrap().id(), item1.id());
2765        });
2766
2767        cx.simulate_prompt_answer(window_id, 0);
2768        cx.foreground().run_until_parked();
2769        pane.read_with(cx, |pane, cx| {
2770            assert_eq!(item1.read(cx).save_count, 1);
2771            assert_eq!(item1.read(cx).save_as_count, 0);
2772            assert_eq!(item1.read(cx).reload_count, 0);
2773            assert_eq!(pane.items().count(), 3);
2774            assert_eq!(pane.active_item().unwrap().id(), item3.id());
2775        });
2776
2777        cx.simulate_prompt_answer(window_id, 1);
2778        cx.foreground().run_until_parked();
2779        pane.read_with(cx, |pane, cx| {
2780            assert_eq!(item3.read(cx).save_count, 0);
2781            assert_eq!(item3.read(cx).save_as_count, 0);
2782            assert_eq!(item3.read(cx).reload_count, 1);
2783            assert_eq!(pane.items().count(), 2);
2784            assert_eq!(pane.active_item().unwrap().id(), item4.id());
2785        });
2786
2787        cx.simulate_prompt_answer(window_id, 0);
2788        cx.foreground().run_until_parked();
2789        cx.simulate_new_path_selection(|_| Some(Default::default()));
2790        close_items.await.unwrap();
2791        pane.read_with(cx, |pane, cx| {
2792            assert_eq!(item4.read(cx).save_count, 0);
2793            assert_eq!(item4.read(cx).save_as_count, 1);
2794            assert_eq!(item4.read(cx).reload_count, 0);
2795            assert_eq!(pane.items().count(), 1);
2796            assert_eq!(pane.active_item().unwrap().id(), item2.id());
2797        });
2798    }
2799
2800    #[gpui::test]
2801    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
2802        cx.foreground().forbid_parking();
2803        Settings::test_async(cx);
2804        let fs = FakeFs::new(cx.background());
2805
2806        let project = Project::test(fs, [], cx).await;
2807        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
2808
2809        // Create several workspace items with single project entries, and two
2810        // workspace items with multiple project entries.
2811        let single_entry_items = (0..=4)
2812            .map(|project_entry_id| {
2813                let mut item = TestItem::new();
2814                item.is_dirty = true;
2815                item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
2816                item.is_singleton = true;
2817                item
2818            })
2819            .collect::<Vec<_>>();
2820        let item_2_3 = {
2821            let mut item = TestItem::new();
2822            item.is_dirty = true;
2823            item.is_singleton = false;
2824            item.project_entry_ids =
2825                vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
2826            item
2827        };
2828        let item_3_4 = {
2829            let mut item = TestItem::new();
2830            item.is_dirty = true;
2831            item.is_singleton = false;
2832            item.project_entry_ids =
2833                vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
2834            item
2835        };
2836
2837        // Create two panes that contain the following project entries:
2838        //   left pane:
2839        //     multi-entry items:   (2, 3)
2840        //     single-entry items:  0, 1, 2, 3, 4
2841        //   right pane:
2842        //     single-entry items:  1
2843        //     multi-entry items:   (3, 4)
2844        let left_pane = workspace.update(cx, |workspace, cx| {
2845            let left_pane = workspace.active_pane().clone();
2846            let right_pane = workspace.split_pane(left_pane.clone(), SplitDirection::Right, cx);
2847
2848            workspace.activate_pane(left_pane.clone(), cx);
2849            workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
2850            for item in &single_entry_items {
2851                workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
2852            }
2853
2854            workspace.activate_pane(right_pane.clone(), cx);
2855            workspace.add_item(Box::new(cx.add_view(|_| single_entry_items[1].clone())), cx);
2856            workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
2857
2858            left_pane
2859        });
2860
2861        // When closing all of the items in the left pane, we should be prompted twice:
2862        // once for project entry 0, and once for project entry 2. After those two
2863        // prompts, the task should complete.
2864        let close = workspace.update(cx, |workspace, cx| {
2865            workspace.activate_pane(left_pane.clone(), cx);
2866            Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
2867        });
2868
2869        cx.foreground().run_until_parked();
2870        left_pane.read_with(cx, |pane, cx| {
2871            assert_eq!(
2872                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
2873                &[ProjectEntryId::from_proto(0)]
2874            );
2875        });
2876        cx.simulate_prompt_answer(window_id, 0);
2877
2878        cx.foreground().run_until_parked();
2879        left_pane.read_with(cx, |pane, cx| {
2880            assert_eq!(
2881                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
2882                &[ProjectEntryId::from_proto(2)]
2883            );
2884        });
2885        cx.simulate_prompt_answer(window_id, 0);
2886
2887        cx.foreground().run_until_parked();
2888        close.await.unwrap();
2889        left_pane.read_with(cx, |pane, _| {
2890            assert_eq!(pane.items().count(), 0);
2891        });
2892    }
2893
2894    #[derive(Clone)]
2895    struct TestItem {
2896        save_count: usize,
2897        save_as_count: usize,
2898        reload_count: usize,
2899        is_dirty: bool,
2900        has_conflict: bool,
2901        project_entry_ids: Vec<ProjectEntryId>,
2902        project_path: Option<ProjectPath>,
2903        is_singleton: bool,
2904    }
2905
2906    impl TestItem {
2907        fn new() -> Self {
2908            Self {
2909                save_count: 0,
2910                save_as_count: 0,
2911                reload_count: 0,
2912                is_dirty: false,
2913                has_conflict: false,
2914                project_entry_ids: Vec::new(),
2915                project_path: None,
2916                is_singleton: true,
2917            }
2918        }
2919    }
2920
2921    impl Entity for TestItem {
2922        type Event = ();
2923    }
2924
2925    impl View for TestItem {
2926        fn ui_name() -> &'static str {
2927            "TestItem"
2928        }
2929
2930        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
2931            Empty::new().boxed()
2932        }
2933    }
2934
2935    impl Item for TestItem {
2936        fn tab_content(&self, _: &theme::Tab, _: &AppContext) -> ElementBox {
2937            Empty::new().boxed()
2938        }
2939
2940        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
2941            self.project_path.clone()
2942        }
2943
2944        fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
2945            self.project_entry_ids.iter().copied().collect()
2946        }
2947
2948        fn is_singleton(&self, _: &AppContext) -> bool {
2949            self.is_singleton
2950        }
2951
2952        fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
2953
2954        fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
2955        where
2956            Self: Sized,
2957        {
2958            Some(self.clone())
2959        }
2960
2961        fn is_dirty(&self, _: &AppContext) -> bool {
2962            self.is_dirty
2963        }
2964
2965        fn has_conflict(&self, _: &AppContext) -> bool {
2966            self.has_conflict
2967        }
2968
2969        fn can_save(&self, _: &AppContext) -> bool {
2970            self.project_entry_ids.len() > 0
2971        }
2972
2973        fn save(
2974            &mut self,
2975            _: ModelHandle<Project>,
2976            _: &mut ViewContext<Self>,
2977        ) -> Task<anyhow::Result<()>> {
2978            self.save_count += 1;
2979            Task::ready(Ok(()))
2980        }
2981
2982        fn save_as(
2983            &mut self,
2984            _: ModelHandle<Project>,
2985            _: std::path::PathBuf,
2986            _: &mut ViewContext<Self>,
2987        ) -> Task<anyhow::Result<()>> {
2988            self.save_as_count += 1;
2989            Task::ready(Ok(()))
2990        }
2991
2992        fn reload(
2993            &mut self,
2994            _: ModelHandle<Project>,
2995            _: &mut ViewContext<Self>,
2996        ) -> Task<anyhow::Result<()>> {
2997            self.reload_count += 1;
2998            Task::ready(Ok(()))
2999        }
3000
3001        fn should_update_tab_on_event(_: &Self::Event) -> bool {
3002            true
3003        }
3004    }
3005}